changing multiple column values given a condition in dplyr

前端 未结 2 896
攒了一身酷
攒了一身酷 2020-12-10 17:42

I\'m looking to find a simple way to do something like the following but with dplyr, essentially just replacing the values in 3 columns with NA when the condition is met.

相关标签:
2条回答
  • 2020-12-10 18:10

    If you instead want a data.frame-wise replacement of a specific value (-99999) in any column for NA:

    dat %>% mutate_all(funs(ifelse(.==-99999, NA, .)))
    
    0 讨论(0)
  • 2020-12-10 18:21

    You can use mutate_at and pass the columns x1,x2,x3 to .vars parameter:

    dta <- data.frame(na.ind = 1:3, x1 = 2:4, x2 = 2:4, x3 = 2:4, x4 = 2:4)
    dta
    #  na.ind x1 x2 x3 x4
    #1      1  2  2  2  2
    #2      2  3  3  3  3
    #3      3  4  4  4  4
    
    dta %>% mutate_at(.vars = c("x1", "x2", "x3"), funs(ifelse(na.ind == 1, NA, .)))
    #  na.ind x1 x2 x3 x4
    #1      1 NA NA NA  2
    #2      2  3  3  3  3
    #3      3  4  4  4  4
    
    0 讨论(0)
提交回复
热议问题