有条件地用NA替换零 [英] replace zeros with NA conditionally in

查看:54
本文介绍了有条件地用NA替换零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 df 中,只有2个服务器场,因此每个 fruit 都是重复的.我想用 NA 替换零,如下所示

In the below df, there are only 2 farms, so each fruit is duplicated. i'd like to replace zeros with NA as follows

df[df==0] <- NA

但是,只要其中一个水果有值,例如 y2019 上的 pear ,其值为 c(0,7),我不想替换 0 . dplyr 解决方案会很棒.

However, whenever there is a value for either of the fruits, such as for a pear at y2019 with values c(0, 7), i'd like not to replace 0. dplyr solution would be great.

样本数据:

df <- data.frame(fruit = c("apple", "apple", "peach", "peach", "pear", "pear", "lime", "lime"),
                    farm = as.factor(c(1,2,1,2,1,2,1,2)), 'y2019' = c(0,0,3,12,0,7,4,6), 
                    'y2018' = c(5,3,0,0,8,2,0,0),'y2017' = c(4,5,7,15,0,0,0,0) )
> df
  fruit farm y2019 y2018 y2017
1 apple    1     0     5     4
2 apple    2     0     3     5
3 peach    1     3     0     7
4 peach    2    12     0    15
5  pear    1     0     8     0
6  pear    2     7     2     0
7  lime    1     4     0     0
8  lime    2     6     0     0

推荐答案

library(dplyr)
df %>%
  group_by(fruit) %>%
  mutate_at(vars(starts_with("y20")), ~ if (any(. != 0)) . else NA_real_) %>%
  ungroup()
# # A tibble: 8 x 5
#   fruit farm  y2019 y2018 y2017
#   <chr> <fct> <dbl> <dbl> <dbl>
# 1 apple 1        NA     5     4
# 2 apple 2        NA     3     5
# 3 peach 1         3    NA     7
# 4 peach 2        12    NA    15
# 5 pear  1         0     8    NA
# 6 pear  2         7     2    NA
# 7 lime  1         4    NA    NA
# 8 lime  2         6    NA    NA

这篇关于有条件地用NA替换零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆