在 R 中动态创建一个新列

Dynamically Create a New Column in R

我正在尝试改进我的代码并避免重复行以导入具有相同名称结构的多个 csvs:

iOS_Weekly_Active_Users_20210301 <- read.csv("iOS_Weekly_Active_Users_20210301.csv", header = T)
iOS_Weekly_Active_Users_20210301$WeekDate <- "2021-03-01"
iOS_Weekly_Active_Users_20210308 <- read.csv("iOS_Weekly_Active_Users_20210308.csv", header = T)
iOS_Weekly_Active_Users_20210308$WeekDate <- "2021-03-08"
iOS_Weekly_Active_Users_20210315 <- read.csv("iOS_Weekly_Active_Users_20210315.csv", header = T)
iOS_Weekly_Active_Users_20210315$WeekDate <- "2021-03-15"
iOS_Weekly_Active_Users_20210322 <- read.csv("iOS_Weekly_Active_Users_20210322.csv", header = T)
iOS_Weekly_Active_Users_20210322$WeekDate <- "2021-03-22"

我设法实现它来读取 csv,但我不知道如何将创建新列 WeekDate 的部分插入到数据框以及我为其提供日期值的位置.

week_date_list <- c("20210301", "20210308", "20210315", "20210322" )

for(week_date in week_date_list){
  
  assign(paste0("iOS_Weekly_Active_Users_", week_date), read.csv(paste0("iOS_Weekly_Active_Users_", week_date, ".csv"), header = T))
         
}

不建议在全局环境中创建多个对象。这可以通过存储在 list 中轻松完成(使用 R 4.1.0 用于 lambda (\(week_date)) 或使用 function(week_date)

lst1 <- lapply(week_date_list, \(week_date) {
          tmp <- read.csv(paste0("iOS_Weekly_Active_Users_", 
                            week_date, ".csv"), header = TRUE)
          tmp$WeekDate <- as.Date(week_date, format = "%Y%m%d")
          tmp
   })

在 OP 的 for 循环中

for(week_date in week_date_list){
  tmp <- read.csv(paste0("iOS_Weekly_Active_Users_", week_date, ".csv"),
             header = TRUE)
   tmp$WeekDate <- as.Date(week_date, format = "%Y%m%d")
   assign(paste0("iOS_Weekly_Active_Users_", week_date), tmp)
 }