0

I have multiple CSV files say 2, and I want to extract the specific column from each file.

filenames <- list.files("path")
for(iter in 1:length(filenames)){
  print(filenames[iter])
  my_csv=read.csv(filenames[iter])

Where, csv1 and csv2 contains columns a1,a2,a3,a4 and b1,b2,b3,b4 respectively. Now I want to fetch column a1 from csv1 and b2 from csv2 where csv number (csv1(1 in this case) matches with coulmn name (a1 in this case)). Likewise b2 from csv2(csv2 matches with colummn name b2.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Kaushik
  • 303
  • 4
  • 11

1 Answers1

0

For reading in csv files I strongly recommend using fread from data.table package (More on that here).

library(data.table)
fileCSV <- list.files(pattern = "csv$")
# This function extracts i column from the csv file
# It doesn't look into colnames
getCSVcolumn <- function(FILE) {
    i <- gsub("csv|\\.", "", FILE)
    foo <- fread(FILE)
    foo[, paste0("V", i), with = FALSE]
}
res <- sapply(fileCSV, getCSVcolumn)
res <- do.call("cbind", res)
colnames(res) <- gsub("\\..*","", colnames(res))
pogibas
  • 27,303
  • 19
  • 84
  • 117