R: Read multiple files and label them based on the file name

前端 未结 1 1418
庸人自扰
庸人自扰 2020-12-22 01:10

I have a folder with about 400 files with the same structure. Each of these file contains 4 columns with no header, corresponding to 4 climate variables. I would need to inc

相关标签:
1条回答
  • 2020-12-22 01:40

    You could put all your files in a new folder/directory, and then create a loop using list.files:

    all.dfs <- list()
    for(filename in list.files("some_dir")) {
       all.dfs[[length(all.dfs) + 1]] <- read.table(filename, ...) 
       # put in read.table call the appropriate arguments, including column names for the existing data in the files
       all.dfs[[length(all.dfs)]]$CODE_PLOT <- sub(".*P(\\d*)C(\\d*)\\.csv", "\\1", filename)
       all.dfs[[length(all.dfs)]]$CODE_COUNTRY <- sub(".*P(\\d*)C(\\d*)\\.csv", "\\2", filename)
    }
    

    Then merging everything into one dataframe...

    big.df <- do.call(rbind, all.dfs)
    

    Haven't tested it but feel free to ask questions in comment.

    0 讨论(0)
提交回复
热议问题