【问题标题】:R dplyr - replace NA with 0 if [duplicate]R dplyr - 如果 [重复] 将 NA 替换为 0
【发布时间】:2020-11-19 00:48:57
【问题描述】:

我有这个数据框

dtf <- data.frame(
    id = seq(1, 4),
    amt = c(1, 4, NA, 123),
    xamt = c(1, 4, NA, 123),
    camt = c(1, 4, NA, 123),
    date = c("2020-01-01", NA, "2020-01-01", NA),
    pamt = c(1, 4, NA, 123)
)

如果 colname 是数字,我想替换所有 NA 值,在我的例子中是 amt、xamt、pamt 和 camt。我正在寻找 dplyr 方式。通常我会使用

replace(is.na(.), 0)

但由于日期列,这不起作用。

【问题讨论】:

  • 如果想使用baseR:rapply(dtf, classes = "numeric", f = function(x) replace(x, is.na(x), 0), how = "replace")

标签: r dplyr


【解决方案1】:

您可以使用across

library(dplyr)
dtf %>% mutate(across(where(is.numeric), ~replace(., is.na(.), 0)))
#mutate_if for dplyr < 1.0.0
#dtf %>% mutate_if(is.numeric, ~replace(., is.na(.), 0))

您也可以从tidyr 使用replace_na

dtf %>% mutate(across(where(is.numeric), tidyr::replace_na, 0))

#  id amt xamt camt       date pamt
#1  1   1    1    1 2020-01-01    1
#2  2   4    4    4       <NA>    4
#3  3   0    0    0 2020-01-01    0
#4  4 123  123  123       <NA>  123

根据@Darren Tsai 的建议,我们也可以使用coalesce

dtf %>% mutate(across(where(is.numeric), coalesce, 0))

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2021-07-02
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    相关资源
    最近更新 更多