Reputation: 39
I have a function like this:
do.call(cbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE,header = FALSE,
col.names = )))
}
Unfortunately, the files I want to read, don't have headers. First I'd like to read only the second column, but it seems like read.csv doesn't have that option. More importantly, I'd like the second column to be named after the filename. How can it be done?
Upvotes: 1
Views: 62
Reputation: 887951
If we use read.csv
, then read the columns, extract the second column with indexing, and name that column as the file name
out <- do.call(cbind, lapply(files, function(x) {
dat <- read.csv(x, stringsAsFactors = FALSE, header = FALSE)[2]
names(dat) <- x
dat
}))
Or using fread
library(data.table)
do.call(cbind, lapply(files, function(x) setnames(fread(x, select = 2), x)))
Upvotes: 1