如何获取字符串并构建工作公式

时间:2018-02-13 19:30:37

标签: r string formula

我有一个数据,其名称作为字符串被带入r。我需要采取这些字符串并生成一个运行的公式。我试图整理一些模仿我实际数据的样本数据。

y = c(1,2,3,4,5,6,7,8,9,10)
x  = c(2,4,6,8,10,12,14,16,18,20)
weights = c(3,6,9,12,15,18,21,24,27,30)
df <- as.data.frame(cbind(y,x, weights))

set.seed(1)
glm_control <- glm.control(maxit = 10)
the_weights <- paste(names(df)[3])
the_preds <- paste(names(df)[-1])
the_target <- paste(names(df)[1])
the_form <- as.formula(paste(the_target, " ~ ", the_preds, ",control =", 
glm_control, ",weights =", the_weights, ",family" = quasipoisson(link = 
"log"), data = df))

我一直收到错误Error in parse(text = x, keep.source = FALSE) : 1: y ~ x

1 个答案:

答案 0 :(得分:0)

我明白了:

y = c(1,2,3,4,5,6,7,8,9,10)
x  = c(2,4,6,8,10,12,14,16,18,20)
weights = c(3,6,9,12,15,18,21,24,27,30)
df <- as.data.frame(cbind(y,x, weights))

set.seed(1)
glm_control <- eval(parse(text = paste0("glm.control(maxit = "10")")))
the_weights <- paste(names(df)[3])
the_preds <- paste(names(df)[-1])
the_target <- paste(names(df)[1])
the_form <-   paste(the_target,  the_preds, sep = "~"

formula <- eval(parse(text = paste0("glm(","the_form,", weights = "the_weights,", family = quasipoisson(link="log"), data = df)")))