执行一个函数作为错误条件 [英] executing a function as an ifelse condition
问题描述
状态< -rep(c(NY,如果没有满足错误条件,我希望执行'myFunc' NJ),times = 5)
Test <-rep(c(LSAT,MCAT,GRE,TOEFL,ACT),times = 2)
Grade< ; -trunc(rep((seq(from = 500,to = 600,length.out = 10))))
dat <-data.frame(Test,State,Grade)
statelist < (LS,MCAT,GRE,TOEFL,ACT,VSAT)
myFunc< -function(state,test)
{
dat< -subset(dat,subset =(State == state& Test == test))
}
ifelse(!state%in%statelist,stop(invalid state),
ifelse(!test%in%testlist,stop(invalid test),
ifelse(myFunc)
当我使用以下变量测试函数时:
myFunc(NY,GRE)
我得到这个错误信息:
错误:意外符号在:
ifelse(myFunc )
myFunc
另外,当我用无效状态测试时,'NN',
myFunc(NN,GRE)
无效状态消息没有被触发,并且生成了与使用有效状态时相同的错误消息。
我的方式有问题吗?我组织了三次ifelse声明?我想保留这个函数的两个错误检查,所以这个函数只处理子集。
我会这样做,如果语句转换为,因为这对我来说更有意义
myFunc< - function(state,test){
dat< - subset(dat,subset =(State == state& Test == test))
if(!状态%在%statelist中)
{stop(invalid state)}
if(!test%in%testlist)
{stop(invalid test)}
else
{return(dat)}
}
R> myFunc(NY,GRE)
测试状态等级
3 GRE NY 522
R> myFunc(NN,GRE)
myFunc错误(NN,GRE):无效状态
R> myFunc(NY,GREY)
myFunc错误(NY,GREY):无效测试
In the following example, I define 'myFunc', then test for two error conditions. If neither error condition is met, I want 'myFunc' to execute.
State<-rep(c("NY","NJ"),times=5)
Test<-rep(c("LSAT", "MCAT", "GRE","TOEFL","ACT"), times=2)
Grade<-trunc(rep((seq(from=500, to=600,length.out=10))))
dat<-data.frame(Test,State,Grade)
statelist<-c("NY","NJ","CA")
testlist<-c("LSAT", "MCAT", "GRE","TOEFL","ACT","VSAT")
myFunc<-function(state,test)
{
dat<-subset(dat,subset=(State==state & Test==test))
}
ifelse(!state %in% statelist, stop("invalid state"),
ifelse(!test %in% testlist, stop("invalid test"),
ifelse(myFunc)
When I test the function with the following variables:
myFunc("NY", "GRE")
I get this error message:
Error: unexpected symbol in:
" ifelse(myFunc)
myFunc"
Also, when I test with an invalid state, 'NN',
myFunc("NN", "GRE")
the "invalid state" message is not triggered, and the same error message is generated that I got when I used a valid state.
Is there a problem with the way I've organized my three ifelse statements? I want to keep the two error checks out of the function, so that the function only deals with subsetting.
Here is how I would do it, I switched to an if
statement since that made more sense to me
myFunc <- function(state,test){
dat <- subset(dat,subset=(State==state & Test==test))
if(!state %in% statelist)
{stop("invalid state")}
if(!test %in% testlist)
{stop("invalid test")}
else
{return(dat)}
}
R> myFunc("NY", "GRE")
Test State Grade
3 GRE NY 522
R> myFunc("NN", "GRE")
Error in myFunc("NN", "GRE") : invalid state
R> myFunc("NY", "GREY")
Error in myFunc("NY", "GREY") : invalid test
这篇关于执行一个函数作为错误条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!