我正在尝试构建一个R闪亮的应用程序,其中我有用户为模型选择变量。用户选择的元素放入向量中。如何删除引号以及在它们选择的每个元素之间放置空格,将其作为模型中的变量?
举个例子:
> vars <- c("cyl", "disp", "hp")
> my.model <- lm(mpg ~ paste(vars, collapse = "+"), data = mtcars)
给出错误:
Error in model.frame.default(formula = mpg ~ paste(vars, collapse = "+"), :
variable lengths differ (found for 'paste(vars, collapse = "+")')
通过阅读Stackoverflow上其他有些类似的问题,有人建议使用as.name()删除引号,但这会产生另一个错误:
> vars <- c("cyl", "disp", "hp")
> my.model <- lm(mpg ~ as.name(paste(vars, collapse = "+")), data = mtcars)
Error in model.frame.default(formula = mpg ~ as.name(paste(vars, collapse = "+")), :
invalid type (symbol) for variable 'as.name(paste(vars, collapse = "+"))'
答案 0 :(得分:2)
公式不仅仅是没有引号的字符串。它是未评估符号的集合。尝试使用reformulate
函数中的内置来构建公式。
vars <- c("cyl", "disp", "hp")
my.model <- lm(reformulate(vars,"mpg"), data = mtcars)
答案 1 :(得分:2)
as.formula
应该能够将字符串强制转换为公式
lm(as.formula((paste("mpg ~", paste(vars, collapse = "+")))), data = mtcars)
#Call:
#lm(formula = as.formula((paste("mpg ~", paste(vars, collapse = "+")))),
# data = mtcars)
#Coefficients:
#(Intercept) cyl disp hp
# 34.18492 -1.22742 -0.01884 -0.01468