简体   繁体   English

R:使用 glm-function 应用列表

[英]R: Apply a list with glm-function

I'm having trouble trying to put variables, which are in list, into a glm -function.我在尝试将列表中的变量放入glm函数时遇到问题。 My dataframe has lots of variables, so it would be too much effort to type the independent variables one by one into glm .我的数据框有很多变量,因此将自变量一个一个地输入到glm会费力。 Lets say my dataframe is假设我的数据框是

df <- data.frame(
  id = c(1,2,3,4,5),
  `sitting position` = c("A","B","A","A","B"),
  `variable one` = c("left", "left", "right", "right", "left"),
  `variable two` = c(50, 30, 45, 80, 57),
  `variable three` = c("m","w","w","m","m"),
  check.names = FALSE)

and my list of columns which I want to use in a glm -function looks like this我想在glm函数中使用的列列表如下所示

columns <- dput(colnames(df))[-c(1:2)]

columns 
[1] "variable one"   "variable two"   "variable three"

Now I want to put this list directly into a glm - function, something like现在我想将此列表直接放入glm - 函数中,类似于

glm(`sitting position` ~ columns, data = df, familiy = binomial).

instead of代替

glm(`sitting position` ~ `variable one` + `variable two` + `variable three`, data = df, family = binomial())

I am aware that I can't work just by adding the list, but I also can't find a solution to fix this problem.我知道我不能仅通过添加列表来工作,但我也找不到解决此问题的解决方案。

Maybe we can use reformulate .也许我们可以使用reformulate reformulate will create formulas from character vectors.重新制定将从字符向量创建公式。 We can feed the output of reformulate into the formula argument to the glm function.我们可以将glm的输出输入到glm函数的formula参数中。

I included a preliminary step to replace your column names with a cleaner and less buggy alternative with janitor::clean_names .我包括了一个初步步骤,用一个更干净、更少错误的替代品替换你的列名和janitor::clean_names

library(janitor)

df<-df %>% clean_names
columns<-c('variable_one', 'variable_two', 'variable_three')

And then the actual solution:然后是实际的解决方案:

glm(formula=reformulate(termlabels = columns, response='sitting_position'), data=df)

See how reformulate works:看看reformulate是如何工作的:

reformulate(termlabels = columns, response='sitting_position')

sitting_position ~ variable_one + variable_two + variable_three

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM