【问题标题】:Replace dash in dataframe using str_replace_all使用 str_replace_all 替换数据框中的破折号
【发布时间】:2019-10-22 06:18:26
【问题描述】:

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

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)

我做错了什么?

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    感谢mutate_at 为我工作,因为我有 21 列带破折号的真实数据,例如

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

    【讨论】:

      【解决方案2】:

      我们可以使用mutate_at

      library(dplyr)
      example %>% mutate_at(vars(Units), list(~as.numeric(str_replace_all(.,'-','0')))) 
      

      【讨论】:

        【解决方案3】:

        stringr::str_replace_all 函数作用于向量,而不是整个数据帧:

        example$Units = example$Units %>%
            str_replace_all("-", "0") %>%
            as.numeric
        

        example <- example %>%
          mutate(Units = Units %>% 
                   str_replace_all("-", "0") %>%
                   as.numeric)
        

        或者你可以更简洁地使用:

        example$Units = readr::parse_number(example$Units)
        

        【讨论】:

        • 感谢您的澄清!
        【解决方案4】:

        df

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-03
          • 2011-08-28
          • 1970-01-01
          • 2011-03-08
          • 2023-03-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多