【问题标题】:Read CSV from list of files and "mutate" a column (date)从文件列表中读取 CSV 并“变异”一列(日期)
【发布时间】:2020-04-12 13:40:32
【问题描述】:

尝试读取多个 CSV 文件,然后汇总到有用的级别,但问题是某些日期是 YYYYMMDD(字符)而其他日期是 DD-MM-YYYY(日期)所以汇总函数分别总结了这些。我已经尝试了 mutate 函数(我的代码在下面),但结果是no applicable method for 'mutate_' applied to an object of class "list"

我也玩过 purrr 中的地图功能,但我不熟悉它,也无法让它工作。

sales_files <- list.files(path = "*folder redacted*", full.names = TRUE) %>%
  lapply(read_csv) %>% 
  mutate(date = case_when(left(date,4) == "2020" ~ as.Date(as.character(date),format="%Y%m%d"), TRUE ~ date))
  group_by(`ID`, `Date`) %>% 
  summarise(sales = sum(`Value`), quantity = sum(`Qty`)) %>% 
  bind_rows

TIA!

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    尝试使用以下方法:

    library(tidyverse)
    library(lubridate)
    
    output <- list.files(path = "*folder redacted*", full.names = TRUE) %>%
                 map_df(~{
                   #Read file name
                   read_csv(.x) %>%
                   #Convert different format date 
                   mutate(date = parse_date_time(date, orders = c('Ymd', 'dmY'))) %>%
                   #Group by ID and Date
                   group_by(ID, Date) %>% 
                   #Sum Value and Qty
                   summarise(sales = sum(Value), quantity = sum(Qty))
               })
    

    【讨论】:

    • 这对我来说似乎很完美,我只需要通过添加一个逗号对 c('Ymd dmY') 进行一点小改动:c('Ymd', 'dmY')。谢谢!
    【解决方案2】:

    我们可以使用anytime中的anydate自动解析多个日期

    library(dplyr)
    library(purrr)
    library(anytime)
    library(readr)
    output <- list.files(path = "*folder redacted*", full.names = TRUE) %>%
                 map_df(~{               
                   read_csv(.x) %>%              
                   mutate(date = anydate(date)) %>%               
                   group_by(ID, Date) %>%                
                   summarise(sales = sum(Value), quantity = sum(Qty))
               })
    

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2014-06-12
      相关资源
      最近更新 更多