0

Let's assume I have this dataframe:

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

And I want to run this formula:

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

Where df2$if_a is a external value from df and it just can take the values 0 or 1 (df2 has just one row). As you can see above, If df2$if_a == 1 I need to run the first "pack" of variables, while if its equal to 0, I need to run the other "pack" of variables.

I have tried as.formula() and reformulate() without success:

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

Also, there are some similar questions (1,2,3). However, they subset the dataframe in the data = argument, and I need to make the formula = argument subject to a value of a external source.

Any suggestions?

Chris
  • 2,019
  • 5
  • 22
  • 67
  • 1
    Does `df2` only have one row? Or does it have the same number of rows as `df`? It would be helpful if your example had all variables defined so it was infact [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Mar 05 '19 at 21:00

1 Answers1

5

Use if (not vectorized ifelse---since you're ((hopefully)) not using a vector) to select the formula you want, rather than trying to use it inside the formula:

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)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294