首页 > 解决方案 > 使用 str_replace_all 替换数据框中的破折号

问题描述

我对这个基本问题感到困惑。我有一个带有破折号而不是零值的数据框,例如

example <- data.frame(Month = c("Jan", "Feb", "March"),
                  Units = c("100", "-", "300"),
                  stringsAsFactors = F)

现在我认为 str_replace_all 会起作用:

replace <- example %>%
  str_replace_all("-", "0")

但我收到这个警告:

Warning message:
In stri_replace_first_regex(string, pattern, fix_replacement(replacement),  :
  argument is not an atomic vector; coercing

在将“单位”转换为数字之前,我需要先进行转换,例如

replace <- example %>%
  str_replace_all("-", "0") %>%
  mutate_at(2, as.numeric)

我究竟做错了什么?

标签: rtidyverse

解决方案


谢谢mutate_at,因为我的真实数据对我有用,我有 21 个带有破折号的列,例如

replace <- real_data %>%
    mutate_at(vars(2:22),list(~as.numeric(str_replace_all(.,'-','0')))))

推荐阅读