Set certain values to NA with dplyr

前端 未结 5 1201
囚心锁ツ
囚心锁ツ 2020-11-28 21:20

I\'m trying to figure out a simple way to do something like this with dplyr (data set = dat, variable = x):

day$x[dat$x<0]=NA

Should be

5条回答
  •  难免孤独
    2020-11-28 21:37

    The most natural approach in dplyr is to use the na_if function.

    For one variable:

    dat %<>% mutate(x = na_if(x, x < 0))
    

    For all variables:

    dat %<>% mutate_all(~ na_if(., . < 0))
    

    If interested in replacing a specific value, instead of a range for all variables:

    dat %<>% mutate_all(na_if, 0)
    

    Note that I am using the %<>% operator from the magrittr package.

提交回复
热议问题