Home > Back-end >  R, sapply(), function, and if/else problem
R, sapply(), function, and if/else problem

Time:09-24

I have to operate over an entire column. I need the value "x" of each row in one column to be:

  • if x < 42, then 0,
  • if x > 364, then 5,
  • if not meeting these conditions I need to multiply 5 by the value in the same row position as x in another column.

I structured the operation like this:

rel$recentness_new <- sapply(rel$`Recentness data (# days)`, function(x) if (x < 42) {
  0
} else if (x > 364) {
    5
} else {
  rel$recentness_relative[x] * 5
})

As you can imagine all works well till the second if, then I get weird values as outputs. I am not sure how to tell R to multiply by the value in the same row but in another column within the function!

CodePudding user response:

ifelse() can work on a whole column at once, and you can stack them, like:

set.seed(1)
a <- runif(n = 100, min = 0, max = 400)
b <- rep(2, 100)
df <- data.frame(a,b)

df$c <- ifelse(df$a < 42, 0, ifelse(df$a > 364, 5, df$b * 5))
head(df)
#>           a b  c
#> 1 106.20347 2 10
#> 2 148.84956 2 10
#> 3 229.14135 2 10
#> 4 363.28312 2 10
#> 5  80.67277 2 10
#> 6 359.35587 2 10
Created on 2021-09-23 by the reprex package (v2.0.1)
  • Related