【发布时间】:2013-12-04 03:47:43
【问题描述】:
我想遍历数据帧中的变量,在每个变量上调用 lm(),所以我写了这个:
findvars <- function(x = samsungData, dv = 'activity', id = 'subject') {
# Loops through the possible predictor vars, does an lm() predicting the dv
# from each, and returns a data.frame of coefficients, one row per IV.
r <- data.frame()
# All varnames apart from the dependent var, and the case identifier
ivs <- setdiff(names(x), c(dv, id))
for (iv in ivs) {
print(paste("trying", iv))
m <- lm(dv ~ iv, data = x, na.rm = TRUE)
# Take the absolute value of the coefficient, then transpose.
c <- t(as.data.frame(sapply(m$coefficients, abs)))
c$iv <- iv # which IV produced this row?
r <- c(r, c)
}
return(r)
}
这不起作用,我相信 b/c lm() 调用中的公式由函数局部变量组成,这些变量在传入的数据帧中保存字符串命名变量(例如,“my_dependant_var”和“this_iv”)而不是指向实际变量对象的指针。
我尝试将该公式包装在 eval(parse(text = )) 中,但无法使其工作。
如果我的问题是正确的,有人可以向我解释如何让 R 将这些 vars iv & dv 的内容解析为我需要的指针吗?或者如果我错了,有人可以解释一下发生了什么吗?
非常感谢!
这是一些重现代码:
library(datasets)
data(USJudgeRatings)
findvars(x = USJudgeRatings, dv = 'CONT', id = 'DILG')
【问题讨论】:
-
?reformulate(您可以搜索该关键字) -
在 R 中你应该忘记“指向对象的指针”。值被传递......作为值。而公式中的“变量”并不是真正的“字符串”。名称和符号是超类“语言”的对象。字符向量不是。
标签: r