R - 在 For 循环中添加带有/文件名的列

R - Add Column w/ File Name on For Loop

我在 for loop 中使用 assing 来批量读取工作目录中的所有 .csv 文件。然后我使用 substr 来清理文件的名称。我想用文件名为每个文件添加一列,以便稍后在代码中进行更好的分析。但是,在清理文件名以添加列后,我无法引用 for loop 中的文件。

#read in all files in folder
files <- list.files(pattern = "*.csv")
for (i in 1:length(files)){
  assign(substr(files[i], start = 11, stop = nchar(files[i])-4),  #clean file names
         read.csv(files[i], stringsAsFactors = FALSE))
  substr(files[i], start = 11, stop = nchar(files[i])-4)['FileFrom'] <- files[i]
}

这行得通吗?

#read in all files in folder
files <- list.files(pattern = "*.csv")
filesCopy <- files
for (i in 1:length(files)){
  assign(substr(files[i], start = 11, stop = nchar(files[i])-4),  #clean file names
         read.csv(files[i], stringsAsFactors = FALSE))
  substr(files[i], start = 11, stop = nchar(files[i])-4)['FileFrom'] <- filesCopy[i]
}

assign 在这里似乎不是正确的功能,我认为您需要在您设置的字符串 cmd 上使用 eval(parse())。行内注释解释更多:

# read in all files in folder
files <- list.files(pattern = "*.csv")

# loop through the files
for (i in 1:length(files)){
  # save the clean filename as a char var because it will be called again
  fnClean = substr(files[i], start = 1, stop = nchar(files[i])-4)

  # create a cmd as a string to be parsed and evaluated on-the-fly
  # the point here is that you can use the 'fnClean' var in the string
  # without knowing what it is - assign is expecting an inline string
  # ...not a string saved as a var, so it can't be used in this case
  loadFileCMD = paste0(fnClean,' = read.csv(files[i], stringsAsFactors = 
    FALSE)')
  print(loadFileCMD) # check the cmd
  eval(parse(text=loadFileCMD))

  # create another string command to be evaluated to insert the file name
  # to the 'FileFrom' field
  addFnCMD = paste0(fnClean,'$FileFrom = files[i]')
  print(addFnCMD) # check the cmd
  eval(parse(text=addFnCMD))
}