【问题标题】:Using substring of file name to create new variable in a list of dataframes使用文件名的子字符串在数据帧列表中创建新变量
【发布时间】:2022-12-18 20:54:51
【问题描述】:

我有一个目录,其中包含一组包含数据帧的 .rds 文件:

files <- c("file_2022-11-30.rds", "file_2022-12-01.rds")

我想将每个文件读入一个列表,然后为列表中的每个数据框分配一个新列,其中包含从(日期)加载的文件的一段名称。我知道如何使用 for 循环执行此操作,但我正在寻找一个简洁的解决方案。我确定有一种方法可以用 lapply 做到这一点,但这不起作用:

library(dplyr)

df_list <- lapply(files, readRDS) %>%
  lapply(FUN = function(x) mutate(date = as.Date(stringr::str_sub(files[x], start = -14, end = -5)))) %>%
bind_rows()

期望的输出看起来像这样:

   var1       date
1     1 2022-11-30
2     2 2022-11-30
3     2 2022-11-30
4     1 2022-11-30
5     2 2022-11-30
6     2 2022-12-01
7     1 2022-12-01
8     2 2022-12-01
9     1 2022-12-01
10    2 2022-12-01

【问题讨论】:

  • 2022-11-31 不是有效日期
  • @akrun 是的,已修复。

标签: r


【解决方案1】:

我们可以在 files 上使用 as.Date 并将其转换为 Date

dates <-  as.Date(files, format = "file_%Y-%m-%d.rds")
do.call(rbind, Map(cbind, lapply(files, readRDS), dates = dates))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2013-04-12
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多