【问题标题】:Convert NA to 0 in columns selected by name using dplyr mutate across [duplicate]使用 dplyr mutate 在按名称选择的列中将 NA 转换为 0 [重复]
【发布时间】:2021-06-06 12:16:30
【问题描述】:

这是我的数据示例

df = data.frame(id = rep(1:3, each = 1), 
                test = sample(40:100, 3), 
                Sets = c(NA,4,4),
                CheWt = c(NA,4,NA),
                LatWt = c(NA,5,5))

我想在标题中有"Wt" 的列中将所有NA 转换为0。我正在尝试使用 dplyr 和 mutate across

df = df%>%
  mutate(across(contains("Wt"), replace(is.na(), 0)))

这是错误

Error: Problem with `mutate()` input `..1`.
x argument "values" is missing, with no default
i Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.

【问题讨论】:

  • replace() 需要 3 个参数,而您只传递了 2 个参数。mutate(across(contains("Wt"), ~ replace(., is.na(.), 0)))
  • df[grep("Wt", names(df))][is.na(df[grep("Wt", names(df))])] <- 0

标签: r na dplyr


【解决方案1】:

replace 需要 3 个参数:值、要替换的值的索引和替换。你需要使用~ 来实现 purrr 风格的匿名函数:

df = df %>%
  mutate(across(contains("Wt"), ~replace(., is.na(.), 0)))
df
#   id test Sets CheWt LatWt
# 1  1   93   NA     0     0
# 2  2   44    4     4     5
# 3  3   80    4     0     5

或者您可以使用replace_na 来获得更简单的界面:

df = df%>%
  mutate(across(contains("Wt"), replace_na, 0))
df
#   id test Sets CheWt LatWt
# 1  1   73   NA     0     0
# 2  2   43    4     4     5
# 3  3   54    4     0     5

【讨论】:

    【解决方案2】:

    这是使用ifelseis.na 的解决方案。

    
    library(dplyr)
    
    
    df = data.frame(id = rep(1:3, each = 1), 
                    test = sample(40:100, 3), 
                    Sets = c(NA,4,4),
                    CheWt = c(NA,4,NA),
                    LatWt = c(NA,5,5))
    
    
    df = mutate(df, across(contains("Wt"), ~ifelse(is.na(.x), 0, .x)))
    
    
    #>   id test Sets CheWt LatWt
    #> 1  1   97   NA     0     0
    #> 2  2   79    4     4     5
    #> 3  3   75    4     0     5
    

    reprex package (v0.3.0) 于 2021-03-08 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2012-10-21
      相关资源
      最近更新 更多