【发布时间】:2017-10-06 18:40:28
【问题描述】:
我正在尝试编写一个最多具有 6 个潜在条件的函数。该函数创建一个线性模型,该模型最多可以有三个参数,并且可以缩放或不缩放。我尝试使用嵌套的 if else 语句,但遇到了问题,因为我有太多条件(缩放或不缩放 X 3ivs 可能 = 6 个潜在条件)。如何简化我的代码,使其更易于阅读?
这是我试图写的,但它目前不起作用。
test<-data.frame(a=sample.int(20,10,replace=T),b=sample.int(20,10,replace=T),c=sample.int(20,10,replace=T),d=sample.int(20,10,replace=T))
lm3iv<-function(dv,iv1,iv2=NA,iv3=NA,df,scale=F){
dn<-dv;in1<-iv1;in2<-iv2;in3<-iv3 #stores the names of variables/elements specified in function
dv<-eval(parse(text=paste0(df,"$",dv))) #Store output of (df,"$",dv) as variable dv; parse=trun string into text; eval=return the values given by an expression that is passed to eval (by parse in this case).
#return(dv)
iv1<-eval(parse(text=paste0(df,"$",iv1)))
if(!is.na(iv2)){iv2<-eval(parse(text=paste0(df,"$",iv2)))}
if(!is.na(iv3)){iv3<-eval(parse(text=paste0(df,"$",iv3)))}
ifelse(scale,
ifelse(!is.na(iv3),
{
x<-lm(scale(dv)~scale(iv1)+scale(iv2)+scale(iv3))
names(x$coefficients)<-c(dn,in1,in2,in3) #set names of coefficients (element of x) from x (object defined in above line); names=pulling specific elements of coefficients
return(summary(x))
},
ifelse(!is.na(iv2),{
x<-lm(scale(dv)~scale(iv1)+scale(iv2))
names(x$coefficients)<-c(dn,in1,in2)
return(summary(x))
},
{
x<-lm(scale(dv)~scale(iv1))
names(x$coefficients)<-c(dn,in1)
return(summary(x))
},
ifelse(!is.na(iv3),
return(summary(lm((dv)~(iv1)+(iv2)+(iv3)))),
ifelse(!is.na(iv2),
return(summary(lm((dv)~(iv1)+(iv2)))),
return(summary(lm((dv)~(iv1)))))))
) #format=ifelse(cond,if_true,if_false)
)
}
#tried adding list() before the first summary to return model outpot and the model its self; have to add the model again after the comma after summary() - e.g., lm(scale(dv)~scale(iv1)+scale(iv2)+scale(iv3))) (same model being summarized). Have to create a variable when passing the data into the model. When reading output -> model.output(model.std.el.ns.tw[[1]],model.std.el.ns.tw[[2]]).
lm3iv("a","b","c","d",df="test",scale=F)
这是我遇到的错误,但我正在尝试简化我的代码,而不仅仅是解决错误:
Error in ifelse(scale, ifelse(!is.na(iv3), { :
argument "no" is missing, with no default
【问题讨论】:
-
ifelse(scale, ... )的语法不合适。必须对 ifelse 语句进行测试。例如,ifelse(scale==T,..., ...) -
我整理了你的代码,你的输出比 ifelses 多……我会整理好回答,以便你看到
-
你应该尽快阅读 help("$")。您对 eval(parse()) 的使用是失礼的,完全没有必要。
标签: r function if-statement