I would like to write a function with multiple conditions within lapply. I know how to define multiple conditions using a for loop. However I would like to avoid looping this time.
For instance:
let's assume there is a vector (vctr) with numbers from -3 to 5:
set.seed(10)
vctr <- c(sample(-3:5), rep(0,3), sample(-3:5), 0)
and let's define two conditions:
- condition_1 <- if the number is equal to 0 -> add 1 to the initial value
- condition_2 <- if the number is not equal to 0 -> leave it be
And this works perfectly fine:
test_list <- lapply(1:length(vctr), function(x) if(vctr[x]==0) vctr[x] 1 else vctr[x])
However, what about the situation in which there would be multiple conditions? For instance:
- condition_1 <- if the number is equal to 0 -> add 1
- condition_2 <- if the number is negative -> replace it with absolute value
- condition_3 <- if the number is greater than 0 but lower than 3 -> add 2 to the initial value
- condition_4 <- if the number is equal or greater than 3 -> leave it be
I tried the following with conditions 1, 2 and "leave it be" however this syntax does not work.
test_list2 <- lapply(1:length(vctr), function(x) if(vctr[x]==0) vctr[x] 1 if else(vctr[x]<0) abs(vctr[x]) else vctr[x])
EDIT: I would like to ask for non-dplyr solutions.
CodePudding user response:
you can replace sapply
with lapply
if you want a list output
sapply(vctr, function(x) {
if (x == 0) y <- x 1
if (x < 0) y <- abs(x)
if (x > 0 & x < 3) y <- x 2
if (x >= 3) y <- x
return(y)
})
[1] 5 2 1 4 1 3 3 3 4 1 1 1 3 2 4 3 1 5 1 3 4 1