Vectorized IF statement in R?

Viewed 75033
x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2

This gives a warning (or error since R version 4.2.0) that the condition has length > 1.

I would want the if to operate on every single case instead of operating on the whole vector. What do I have to change?

6 Answers
nzMean <- function(x) { mean(x[x!=-1],na.rm=TRUE)}

nzMin <- function(x) {min(x[x!=-1],na.rm=TRUE)}

nzMax <- function(x) { max(x[x!=-1],na.rm=TRUE)}

nzRange<-function(x) {nzMax(x)-nzMin(x)}

nzSD <- function(x) { SD(x[x!=-1],na.rm=TRUE)}

#following function works
nzN1<- function(x) {ifelse(x!=-1,(x-nzMin(x))/nzRange(x) ,x) }

#following is bad as it returns only 4 not 5 elements of vector
nzN2<- function(x) {ifelse(x!=-1,(x[x!=-1]-nzMin(x))/nzRange(x) ,x) }

#following is bad as it returns 5 elements of vector but not correct answer
nzN3<- function(x) {ifelse(x!=-1,(x[x!=-1]-nzMin(x))/nzRange(x) ,-1) }

y<-c(1,-1,-20,2,4)
a<-nzMean(y)
b<-nzMin(y)
c<-nzMax(y)
d<-nzRange(y)
# test the working function
z<-nzN1(y)

print(z)
Related