问题
In the code below, df.pts is a dataframe. I'd like to run about dozen glm models using different y variable (only two shown in the code). I'm using a for loop with the paste() function, but I can't seem to get the paste() function to work properly. What am I missing with paste()?
SPCA2 = df.pts[,3]
CLQU2 = df.pts[,4]
df.list = list(SPCA2, CLQU2)
for (i in df.list) {
qp.mod = glm(paste(i,"~NDVI+ELEV"), family="quasipoisson", data=my.data)
print(summary(gp.mod))
}
回答1:
Many thanks! The main problem was that df.list was a list of vectors, and should have been a list of names.
I other words, to correct the problem...
df.list = ("SPCA2", "CLQU2")
instead of
df.list = list(SPCA2, CLQU2)
However, it was also correctly pointed out that the dataframe, my.data, was not the correct dataframe. Finally, while it worked without it, the function as.formula() also worked. Again, many thanks!
回答2:
You need to add as.formula
before paste
to let R know you want to treat it as a formula instead of characters.
qp.mod = glm(as.formula(paste(i,"~NDVI+ELEV")), family="quasipoisson", data=my.data)
来源:https://stackoverflow.com/questions/29553707/using-paste-in-a-for-loop-with-glm