R:应用带有 glm 函数的列表
R: Apply a list with glm-function
我在尝试将列表中的变量放入 glm
函数时遇到问题。我的数据框有很多变量,所以将自变量一个一个地输入 glm
会很费力。可以说我的数据框是
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)
我想在 glm
函数中使用的列列表如下所示
columns <- dput(colnames(df))[-c(1:2)]
columns
[1] "variable one" "variable two" "variable three"
现在我想将这个列表直接放入一个 glm
- 函数中,类似于
glm(`sitting position` ~ columns, data = df, familiy = binomial).
而不是
glm(`sitting position` ~ `variable one` + `variable two` + `variable three`, data = df, family = binomial())
我知道我无法仅通过添加列表来工作,但我也找不到解决此问题的方法。
也许我们可以使用 reformulate
。 reformulate 将从字符向量创建公式。我们可以将 reformulate 的输出提供给 glm
函数的 formula
参数。
我包括了一个初步步骤,用 janitor::clean_names
.
library(janitor)
df<-df %>% clean_names
columns<-c('variable_one', 'variable_two', 'variable_three')
然后是实际的解决方案:
glm(formula=reformulate(termlabels = columns, response='sitting_position'), data=df)
查看 reformulate
的工作原理:
reformulate(termlabels = columns, response='sitting_position')
sitting_position ~ variable_one + variable_two + variable_three
我在尝试将列表中的变量放入 glm
函数时遇到问题。我的数据框有很多变量,所以将自变量一个一个地输入 glm
会很费力。可以说我的数据框是
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)
我想在 glm
函数中使用的列列表如下所示
columns <- dput(colnames(df))[-c(1:2)]
columns
[1] "variable one" "variable two" "variable three"
现在我想将这个列表直接放入一个 glm
- 函数中,类似于
glm(`sitting position` ~ columns, data = df, familiy = binomial).
而不是
glm(`sitting position` ~ `variable one` + `variable two` + `variable three`, data = df, family = binomial())
我知道我无法仅通过添加列表来工作,但我也找不到解决此问题的方法。
也许我们可以使用 reformulate
。 reformulate 将从字符向量创建公式。我们可以将 reformulate 的输出提供给 glm
函数的 formula
参数。
我包括了一个初步步骤,用 janitor::clean_names
.
library(janitor)
df<-df %>% clean_names
columns<-c('variable_one', 'variable_two', 'variable_three')
然后是实际的解决方案:
glm(formula=reformulate(termlabels = columns, response='sitting_position'), data=df)
查看 reformulate
的工作原理:
reformulate(termlabels = columns, response='sitting_position')
sitting_position ~ variable_one + variable_two + variable_three