using paste() in a for loop with glm

。_饼干妹妹 提交于 2019-12-12 01:28:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!