In a large dataframe (\"myfile\") with four columns I have to add a fifth column with values conditionally based on the first four columns.
Prefer answers with
It looks like derivedFactor from the mosaic package was designed for this. In this example, it would look something like:
library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
"1" = (V1==1 & V2!=4),
"2" = (V2==4 & V3!=1),
.method = "first",
.default = 0
))
(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor with an as.numeric.)
Note that the .default option combined with .method = "first" sets the "else" condition -- this approach is described in the help file for derivedFactor.