[R] apply if else statement to vector

Berend Hasselman bhh at xs4all.nl
Thu Oct 2 11:14:17 CEST 2014


On 02-10-2014, at 11:01, rl at openmailbox.org wrote:

> Subscribers,
> 
> What is the correct syntax to apply the 'if else' conditional statement to vector objects?
> 
> Example:
> 
> vectorx<-c(50,50,20,70)
> vectory<-c(50,50,20,20)
> vectorz<-function () {
> 	if (vectorx>vectory)
> 	vectorx
> 	else vectorx<-0
> }
> 
> vectorz()
> Warning message:
> In if (vectorx > vectory) vectorx else vectorx <- 0 :
>  the condition has length > 1 and only the first element will be used
> 
> The help manual (?'if') explains that only length=0 is acceptable; what is an appropriate alternative function to use please?
> 

And at the bottom of that page (section See Also) there is a reference to ifelse. Why didn’t you have a look at that?

Replace your complete if/else statement with ifelse(vectorx>vectory,vectorx,0)

Berend


> 
> 0 0 0 70
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list