ramen
ramen

Reputation: 790

Multiple conditional statements within lapply function to avoid looping

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:

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:

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.

Upvotes: 1

Views: 90

Answers (1)

Wimpel
Wimpel

Reputation: 27802

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

Upvotes: 1

Related Questions