Can dplyr package be used for conditional mutating?

前端 未结 5 1730
庸人自扰
庸人自扰 2020-11-22 15:10

Can the mutate be used when the mutation is conditional (depending on the values of certain column values)?

This example helps showing what I mean.

s         


        
5条回答
  •  名媛妹妹
    2020-11-22 15:27

    The derivedFactor function from mosaic package seems to be designed to handle this. Using this example, it would look like:

    library(dplyr)
    library(mosaic)
    df <- mutate(df, g = derivedFactor(
         "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
         "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         .method = "first",
         .default = NA
         ))
    

    (If you want the result to be numeric instead of a factor, you can wrap derivedFactor in an as.numeric call.)

    derivedFactor can be used for an arbitrary number of conditionals, too.

提交回复
热议问题