Import many .txt files, combine them into one data

2019-07-27 13:59发布

I have many .txt files. You can download 2 of them from here. I imported them into RStudio and combined them into one data.frame using the code below

setwd("C:/Users/aelwan/Dropbox/import_txt")
data<-do.call(rbind, lapply(list.files(pattern = ".txt"), 
                            read.table, 
                            header=T))
    head(data, 12)
     observed    simulated
1         2         4
2         5         5
3         5         2
4         2         5
5         5         2
6         2        12
7         1        56
8         2        75
9         3        78
10        6        75
11        7        65
12        7        53

I'd like to add the file name as well to the data.frameto be like below

     observed    simulated    ID
1         2         4         simu1           
2         5         5         simu1
3         5         2         simu1
4         2         5         simu1
5         5         2         simu1
6         2        12         simu1
7         1        56         simu2
8         2        75         simu2
9         3        78         simu2
10        6        75         simu2
11        7        65         simu2
12        7        53         simu2

Any suggestions how to do that?

1条回答
趁早两清
2楼-- · 2019-07-27 14:46

If you use a for loop then you can add the numerical label column you want:

files.list <- list.files(pattern = ".txt")
df <- data.frame(observed=integer(),
                 simulated=integer(),
                 ID=character(),
                 stringsAsFactors=FALSE)

for (i in 1: length(files.list)) {
    df.next <- read.table(files.list[[i]], header=TRUE)
    df.next$ID <- paste0('simu', i)
    df <- rbind(df, df.next)
}
查看更多
登录 后发表回答