代码之家  ›  专栏  ›  技术社区  ›  alexb523

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

  •  2
  • alexb523  · 技术社区  · 7 年前

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

    #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]
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Justin Braaten    7 年前

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

    # 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))
    }
    
        2
  •  0
  •   Oriol Mirosa    7 年前

    #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]
    }