0

I have a variable list called working_dir that consists of the name of files I want to import

working_dirs
$`./.\\dataset/UCI HAR Dataset/test/Inertial Signals`
[1] "body_acc_x_test.txt"  "body_acc_y_test.txt"  "body_acc_z_test.txt"  "body_gyro_x_test.txt"
[5] "body_gyro_y_test.txt" "body_gyro_z_test.txt" "total_acc_x_test.txt" "total_acc_y_test.txt"
[9] "total_acc_z_test.txt"

$`./.\\dataset/UCI HAR Dataset/train/Inertial Signals`
[1] "body_acc_x_train.txt"  "body_acc_y_train.txt"  "body_acc_z_train.txt"  "body_gyro_x_train.txt"
[5] "body_gyro_y_train.txt" "body_gyro_z_train.txt" "total_acc_x_train.txt" "total_acc_y_train.txt"
[9] "total_acc_z_train.txt"

I want to import each of the files with read.table() and name it with the name of the file. My idea is to use mapply() and pass each argument into assign() function. something like

mapply(assign , working_dir, read.table(working_dir , header = T))

However I know this syntax is incorrect. What are they ways to achieve this?

Omar113
  • 210
  • 1
  • 7
  • The list is called working_dirs in your R environment. – spazznolo Jun 26 '19 at 15:14
  • @spazznolo yes just a variable name – Omar113 Jun 26 '19 at 15:15
  • Read [this](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad) on using `assign`. Btw you can read the files in a `list` of `data.frame`s like this: `ldf = lapply(working_dirs, function(t){read.table(t,header=TRUE)}` then you can also name each element of `list` like: `names(ldf) = working_dirs` – tushaR Jun 26 '19 at 15:28
  • @tushaR your code is not working for me. Please see the structure of the dirs above. I need a way for multiple looping; one for each list item and one for the subitems – Omar113 Jun 26 '19 at 15:31
  • @Omar113 the name of list elements are the folder paths?? also, which OS are you using? How did you create this list? The best way to get paths of files is using `list.files()` `list.files(path = ,full.names = TRUE)` – tushaR Jun 26 '19 at 15:35
  • Possible duplicate of [How to import multiple .csv files at once?](https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once) – ahmad Jun 26 '19 at 15:39

2 Answers2

0

Try this:

ldf=mapply(function(x,y){read.table(paste0(x,y,sep="/"),header=TRUE)},working_dir,names(working_dir))
tushaR
  • 3,083
  • 1
  • 20
  • 33
0

I wrote as script that worked for me.

library(stringr)


folders <- list.dirs()
working_dirs <- lapply( folders, function(x){ list.files(x , full.names = T) })[c(5 ,7)]


for(i in 1:length(working_dirs)){
  dire <-  working_dirs[[i]]
  direnames <- str_extract(working_dirs[[i]] , pattern = "(test|train)(.*)(\\.txt)?")
  for (ii in 1:length(dire)){
    assign(direnames[ii] , read.table(dire[ii]))
  }
}

This will give a separate dataframe for the 18 file!

Omar113
  • 210
  • 1
  • 7