将 NA 值替换为组中的数值

标签 r dataframe dplyr na

我对将 NA 值替换为数据中的数值有疑问。 如果组中的所有行均为 NA,则将其替换为 100,否则 如果组中有任何数值,请将 NA 替换为这些数值。

类似的帖子 How to copy value of a cell to other rows based on the value of other two columns?

replace NA value with the group value

但是我宁愿有直接的 dplyr 解决方案,但这两篇文章有 zoo 包的解决方案!

df = data.frame(gr=gl(3,3),id=c("NA","NA","NA",131,"NA","NA",232,232,"NA"))

> df
  gr  id
1  1  NA
2  1  NA
3  1  NA
4  2 131
5  2  NA
6  2  NA
7  3 232
8  3 232
9  3  NA

看起来很简单,所以我尝试了一下,

library(dplyr)
df%>%
  group_by(gr)%>%
  mutate(id_new=ifelse(all(is.na(id)),100,ifelse(any(is.numeric(id)),id[which(is.numeric(id))],NA)))

# A tibble: 9 x 3
# Groups:   gr [3]
      gr     id id_new
  <fctr> <fctr>  <lgl>
1      1     NA     NA
2      1     NA     NA
3      1     NA     NA
4      2    131     NA
5      2     NA     NA
6      2     NA     NA
7      3    232     NA
8      3    232     NA
9      3     NA     NA

所有行都是NA,为什么?

预期输出

      gr     id id_new
  <fctr> <fctr>  <lgl>
1      1     NA     100
2      1     NA     100
3      1     NA     100
4      2    131     131
5      2     NA     131
6      2     NA     131
7      3    232     232
8      3    232     232
9      3     NA     232

最佳答案

只需将id转换为数字即可。另外,对于 ifelese 的 else 条件,我使用了 max 以防值不唯一。将其更改为适合您的任何内容。我认为不需要复杂的 else 语句。

df%>%
  group_by(gr)%>%
  mutate(id = as.numeric(id)) %>%
  mutate(id_new=ifelse(all(is.na(id)),100,max(id, na.rm = TRUE)))

关于将 NA 值替换为组中的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605115/

相关文章:

r - 根据多列排列长格式数据框并考虑改变排序方向

r - 使用 dplyr 格式化 summarise_each 中的输出

r - 使用不同变量组合运行模型的最佳方法

python - 如何在 Pandas 的一次热编码中处理未知的分类值

python - 使用 Pandas 将月度数据重新采样为年度数据,但从某个月份开始

r - 如何从 df 中对多个列进行子集化,包括 grep match

r - 如何将 lapply 与 mutate 函数一起使用

r - 对于循环存储问题

R:将输入变量转为字符串 - `deparse(substitute(x))` 不起作用

r - 将抖动数据点添加到带有误差线的晶格 xYplot 中