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

时间:2017-08-22 16:27:25

标签: r formula

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

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="+")))
)

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

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

Formula12:

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

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

1 个答案:

答案 0 :(得分:2)

all.vars将为您提供公式中没有重复项的名称列表。这样,如果x部分中也存在公式y部分中的任何内容,则不会显示。然后,您可以使用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