0
votes

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))))                   
)}
1
@李哲源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
You should probably also read this question and not attempt to use assign.joran
@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
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 yDaphFab

1 Answers

0
votes

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.