Chr*_*ris 0 r formula linear-regression lm
假设我有这个数据框:
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
Run Code Online (Sandbox Code Playgroud)
我想运行以下公式:
c_SA=lm(formula = GN1 ~ ifelse(df2$if_a == 1,PEC3+PEC4+AC6,GN2+GN3+E10+PSV7+PEC3), data = df)
Run Code Online (Sandbox Code Playgroud)
df2$if_a来自的外部值在哪里df,它可以取值0或1(df2仅一行)。从上面可以看到,如果df2$if_a == 1我需要运行变量的第一个“ pack”,而如果它等于0,则需要运行变量的另一个“ pack”。
我曾尝试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)
Run Code Online (Sandbox Code Playgroud)
此外,还有一些类似的问题(1,2,3)。但是,它们将data =参数中的数据帧作为子集,而我需要使formula =参数服从外部源的值。
有什么建议么?
使用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)
Run Code Online (Sandbox Code Playgroud)