Can dplyr package be used for conditional mutating?

前端 未结 5 1905
庸人自扰
庸人自扰 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:39

    case_when is now a pretty clean implementation of the SQL-style case when:

    structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
    2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
    5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
    2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
    8L), class = "data.frame") -> df
    
    
    df %>% 
        mutate( g = case_when(
                    a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                    a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
    ))
    

    Using dplyr 0.7.4

    The manual: http://dplyr.tidyverse.org/reference/case_when.html

提交回复
热议问题