lm()和ifelse()语句 - R.

问题描述 投票:0回答:1

我们假设我有这个数据帧:

df <- data.frame(GN1 = sample(1:10, 10 ,replace=TRUE),
           GN2 = sample(1:10, 10 ,replace=TRUE),
           GN3 = sample(1:10, 10 ,replace=TRUE),
           E10 = sample(1:10, 10 ,replace=TRUE),
           PSV7 = sample(1:10, 10 ,replace=TRUE),
           PEC3 = sample(1:10, 10 ,replace=TRUE),
           PEC4 = sample(1:10, 10 ,replace=TRUE),
           AC6 = sample(1:10, 10 ,replace=TRUE),
           AC7 = sample(1:10, 10 ,replace=TRUE),
           stringsAsFactors = FALSE)

   GN1 GN2 GN3 E10 PSV7 PEC3 PEC4 AC6 AC7
1    7   3  10   6    4    4    3   9   3
2    2   5   6   6    6    6    5   7   1
3    7   6  10   6    9    1    9   7   5
4    7   1   8   9    2    4    5   5   7
5    8   3   3   8    6    8    9   5  10
6    7   1   1   8    9    3    8   9   4
7    4   6   4   7    2    6    9   8   9
8    7   8   8   7    2    1    7   6   5
9    1   9   4   8    5    5    2   7   1
10   4   9   2   1    4    4   10   2   9

我想运行这个公式:

c_SA=lm(formula = GN1 ~ ifelse(df2$if_a == 1,PEC3+PEC4+AC6,GN2+GN3+E10+PSV7+PEC3), data = df)

其中df2$if_a是来自df的外部值,它可以取值01df2只有一行)。如上所示,如果df2$if_a == 1我需要运行第一个“包”变量,而如果它等于0,我需要运行另一个“包”变量。

我尝试过as.formula()reformulate()没有成功:

c_SA=lm(formula = GN1 ~ ifelse(df2$if_a == 1,as.formula(PEC3+PEC4+AC6),as.formula(GN2+GN3+E10+PSV7+PEC3)), data = df)

此外,还有一些类似的问题(123)。但是,它们在data =参数中对数据帧进行了子集化,并且我需要使formula =参数服从外部源的值。

有什么建议?

r formula linear-regression lm
1个回答
5
投票

使用if(不是矢量化ifelse ---因为你((希望))不使用矢量)来选择你想要的公式,而不是试图在公式中使用它:

my_formula = if (df2$if_a == 1) {
  GN1 ~ PEC3 + PEC4 + AC6
} else {
 GN1 ~ GN2 + GN3 + E10 + PSV7 + PEC3
}

c_SA = lm(formula = my_formula, data = df)
© www.soinside.com 2019 - 2024. All rights reserved.