lapply - Reading and naming multiple .txt files in R -


i want read , name multiple .txt files in r. more clear (sample): have 2 subfolders, each 1 3 .txt files (they have same name). subfolder 'test' has 3 .txt files names 'alpha.txt','bita.txt','gamma.txt' , subfolder 'train' has 3 .txt files names 'alpha.txt','bita.txt','gamma.txt'. using following code:

files <- dir(recursive=true,pattern ='\\.txt$') list <- lapply(files,read.table,fill=true) 

which gives list 6 elements, each 1 data frane. know first element 'alpha' test folder, second element 'bita' test folder , on. files more read data in order have in environment variables: 'test_alpha','test_bita','test_gamma','train_alpha','train_bita','train_gamma'. there way it?

i created 2 folders in working directory /train , /test. create 2 arrays , write them 1 each folder.

df1 <- data.frame(matrix(rnorm(9), 3, 3)) df2 <- data.frame(matrix(runif(12), 4,3)) write(df1, './test/alpha.txt') write(df2, './train/alpha.txt') 

we run code:

files <- dir(recursive=true,pattern ='\\.txt$') list <- lapply(files,read.table,fill=true)  files [1] "test/alpha.txt"  "train/alpha.txt" 

it works isolate files need. next take out forward slash , file extension.

newnames <- gsub('/', '_', files) newnames1 <- gsub('\\.txt', '', newnames) newnames1 [1] "test_alpha"  "train_alpha" 

this vector can assigned list name each array.

names(list) <- newnames1 list $test_alpha           v1          v2         v3         v4        v5 1 -0.6594299 -0.01881557  0.7076588 -0.7096888 0.3629274 2 -1.4401000  1.59659000 -1.9041430  2.3079960        na  $train_alpha          v1        v2        v3        v4        v5 1 0.9307107 0.6257928 0.6903179 0.5143920 0.6798936 2 0.3652738 0.9297527 0.1902556 0.7243708 0.4541548 3 0.5565041 0.5276907        na        na        na 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -