0

I am trying to import a folder full of multiple .csv files in R and read 2nd and 3rd columns of all the files. I have used the following command, but it throws an error saying "Error in file(file, "rt") : invalid 'description' argument The code is here

folder <-"C:\\\\Users\\USER\\Desktop\\LABWORK\\ECGV0007_everyRRQTinputIntoEntropy_csv" 
file_list <- list.files(path=folder, pattern="*.csv") 
for (i in 1:length(file_list)){   
    assign(file_list[i],
          x <-read.csv(paste(folder, file_list[i], sep=" ",
              fill=TRUE, colClasses=c('null', 'numeric', rep('null',6)))),
                   y <-read.csv(paste(folder, file_list[i], sep=" ",fill=TRUE, colClasses=c(rep('null',2), 'numeric', rep('null',5))))                   
)}
DTYK
  • 1,098
  • 1
  • 8
  • 33
DaphFab
  • 81
  • 8
  • @李哲源ZheyuanLi it does if you escape it, which Daphne did. But the parentheses are placed wrong and the code itself doesn't really make sense actually. – Joris Meys Mar 16 '17 at 18:24
  • You should probably also read [this](http://stackoverflow.com/q/11433432/324364) question and not attempt to use `assign`. – joran Mar 16 '17 at 18:24
  • @joran Do u mean to say that I should remove the entire for loop and use this temp = list.files(pattern="*.csv") myfiles = lapply(temp, read.delim) – DaphFab Mar 16 '17 at 18:34
  • I am trying to import multiple .csv files of the same type in a single folder. I am assigning column 2 of these files as variable x and column 3 as variable y – DaphFab Mar 16 '17 at 18:36

1 Answers1

0

If your csv files all have the same column headers, then I think this will work for what you're trying to accomplish:

folder <-"C:\\\\Users\\USER\\Desktop\\LABWORK\\ECGV0007_everyRRQTinputIntoEntropy_csv" 
file_list - list.files(path = folder, pattern = "*.csv", full.names = T)

dfs <- list()

for(i in 1:length(file_list)) {

    # read in the ith csv
    temp_df <- read.csv(file = file_list[[i]], stringsAsFactors = F)

    # store in a list
    dfs[[i]] <- temp_df
}


# combine all data frames in the list into a single data frame
combined_df <- do.call(rbind, dfs)


# extract 2nd col into x and 3rd col into y
x <- combined_df[, 2]
y <- combined_df[, 3]

Edit:

Added full.names = T to the file_list object so you don't have to paste the folder and file name together.

TaylorV
  • 846
  • 9
  • 13
  • Upon executing the line combined_df <- do.call(rbind, dfs) I get an error stating Error in match.names(clabs, names(xi)) :names do not match previous names – DaphFab Apr 06 '17 at 16:23