Importing and indexing multiple files

I have n files, file_1, file_2, ..., file_n that I want to import and work with. So I import 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 thing is, I want to use data from different files at the same time. For example, I want to calculate 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 it - write a loop that passes through all of the files ( file_1, file_2, ..., file_n). In this case, you need to index the files. Are there any solutions? Or there is another solution.

+1
source share
2 answers

Just use the 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 
+1
source

Here is the 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) 
0

Source: https://habr.com/ru/post/1537194/


All Articles