Importing several files and indexing them

2019-08-05 04:52发布

问题:

I have n files, file_1, file_2,..., file_n that I want to import and work with. So I import the files like this

files <- list.files(pattern=".txt$") 
for(i in files) { 
    x <- read.table(i, header=TRUE, comment.char = "A", sep="\t")
    assign(i, x)
}

The point is that I want to use data simultaneously from the different files. For example I want to compute the means vector of the first column of each file:

 meanv = mean(file_1$firstcolumn, file_2$firstcolumn, ..., file_n$firstcolumn).

the most logical way to do this is the write a loop going through all files (file_1, file_2,..., file_n). In this case you need to index the files. Is there any solution to this? Or is there any other solution.

回答1:

Just use a list:

##Generate some test data
R> dd1 = data.frame(V1 = rnorm(10), V2 = rnorm(10))
R> dd2 = data.frame(V1 = rnorm(10), V2 = rnorm(10))
#Create an empty list
R> l = list()
##In your example, you would have something like:
##l[[i]] = read.table(....)
R> l[[1]] = dd1; l[[2]] = dd2

##Now use lapply to calculate the column means for each data frame
R> lapply(l, colMeans)
[[1]]
     V1      V2 
-0.6805 -0.0767 

[[2]]
      V1       V2 
0.253563 0.006207 


回答2:

Here is an approach

# list files with .txt extension
files  <- list.files(pattern = '\\.txt$')

# read files into a list of tables
tables <- lapply(files, read.table, header = TRUE, comment = 'A', sep = '\t')

# compute mean of first column
meanv <- lapply(tables, colMeans)