从R中公式的x部分中删除y部分

Remove y part from the x part in formula in R

我有 12 个数据帧的列表。一个数据框如下所示:

df12<-data.frame(a.Boston=c(8,8),a.Hartford=c(6,6),a.Denver=c(8,8),b.Boston_12=c(8,8),b.Denver_12=c(6,6))

df12:

   a.Boston a.Hartford a.Denver b.Boston_12 b.Denver_12
    1        8          6        8           8           6
    2        8          6        8           8           6

我正在尝试为每个数据框创建公式。代码如下 用于创建公式:

myformula<-lapply(1:12, function(x) as.formula(paste(paste0("a.", df[['city']][1], " ~ "), 
                                                     paste(sprintf("`%s`", colnames(get(paste0("df",x)))), collapse="+")))
)

我的公式也包含 x 中的 y 部分。例如:

公式 10:

a.Boston ~ a.Boston + a.Hartford + a.Denver + b.Boston_10 + b.Boston_11 + 
  b.Boston_12 + b.Denver_10 + b.Denver_11 + b.Denver_12

公式12:

a.Boston ~ a.Boston + a.Hartford + a.Denver + b.Boston_12 + b.Denver_12

所以,我想从公式中的 x 部分中删除 y 部分。

all.vars 将为您提供公式中没有重复的名称列表。这样,如果 y 部分也存在,则公式的 x 部分中的任何内容都不会出现。然后你可以使用 reformulate 创建公式。

formula10 = a.Boston ~ a.Boston + a.Hartford + a.Denver + b.Boston_10 +
            b.Boston_11 + b.Boston_12 + b.Denver_10 + b.Denver_11 + b.Denver_12
reformulate(all.vars(formula10)[-1], all.vars(formula10)[1])
#a.Boston ~ a.Hartford + a.Denver + b.Boston_10 + b.Boston_11 + 
#    b.Boston_12 + b.Denver_10 + b.Denver_11 + b.Denver_12