jeudi 23 septembre 2021

R, sapply(), function, and if/else problem

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!

Aucun commentaire:

Enregistrer un commentaire