【问题标题】:R - identify which columns contain currency data $R - 识别哪些列包含货币数据 $
【发布时间】:2018-07-16 23:58:39
【问题描述】:

我有一个非常大的数据集,其中一些列格式化为货币、一些数字、一些字符。在读取数据时,所有货币列都被标识为因子,我需要将它们转换为数字。数据集太宽,无法手动识别列。我试图找到一种编程方式来识别列是否包含货币数据(例如以“$”开头),然后传递要清理的列列表。

name <- c('john','carl', 'hank')
salary <- c('$23,456.33','$45,677.43','$76,234.88')
emp_data <- data.frame(name,salary)

clean <- function(ttt){
as.numeric(gsub('[^a-zA-z0-9.]','', ttt))
}
sapply(emp_data, clean)

此示例中的问题是,此 sapply 适用于所有列,导致名称列被替换为 NA。我需要一种以编程方式仅识别需要应用清理函数的列的方法。在这个示例中,薪水。

【问题讨论】:

    标签: r currency data-cleaning


    【解决方案1】:

    使用dplyrstringr 包,您可以使用mutate_if 来识别具有以$ 开头的任何字符串的列,然后进行相应的更改。

    library(dplyr)
    library(stringr)
    
    emp_data %>%
      mutate_if(~any(str_detect(., '^\\$'), na.rm = TRUE),
                ~as.numeric(str_replace_all(., '[$,]', '')))
    

    【讨论】:

    • 谢谢 zack,这非常简洁,完全符合我的要求!
    • @zack ~ 做什么?
    • ~as.numeric(str_replace_all(., '[$,]', '')) 可以替换为 readr::parse_number
    • @Aurèle,是的,我不明白为什么不这样做。 @Ben G,它标志着 purrr 风格的匿名函数的开始。 Quick blurb here if you're interested. 指的是输入列。
    • 发现 1 个错误。如果数据框有数字或整数列,则代码错误。我不熟悉使用这些包,有没有办法为这些列添加转义。
    【解决方案2】:

    利用readr 包提供的强大解析器,开箱即用:

    my_parser <- function(col) {
      # Try first with parse_number that handles currencies automatically quite well
      res <- suppressWarnings(readr::parse_number(col))
      if (is.null(attr(res, "problems", exact = TRUE))) {
        res
      } else {
        # If parse_number fails, fall back on parse_guess
        readr::parse_guess(col)
        # Alternatively, we could simply return col without further parsing attempt
      }
    }
    
    library(dplyr)
    
    emp_data %>% 
      mutate(foo = "USD13.4",
             bar = "£37") %>% 
      mutate_all(my_parser)
    
    #   name   salary  foo bar
    # 1 john 23456.33 13.4  37
    # 2 carl 45677.43 13.4  37
    # 3 hank 76234.88 13.4  37
    

    【讨论】:

      【解决方案3】:

      基本 R 选项是使用 startsWith 检测美元列,并使用 gsub 从列中删除 "$"","

      doll_cols <- sapply(emp_data, function(x) any(startsWith(as.character(x), '$')))
      emp_data[doll_cols] <- lapply(emp_data[doll_cols], 
                                    function(x) as.numeric(gsub('\\$|,', '', x)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 2022-11-28
        • 2014-03-25
        相关资源
        最近更新 更多