dplyr mutate with conditional values

后端 未结 3 2142
我寻月下人不归
我寻月下人不归 2020-11-27 10:34

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

3条回答
  •  情书的邮戳
    2020-11-27 11:04

    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.

提交回复
热议问题