user45292 user45292 - 15 days ago 9
R Question

Create Data frame in R

I want to merge the files row-wise but some of the files have different number of rows (0 as well).I am getting the following error in R:

fileList <- list.files(, pattern=".txt")
new_df=do.call(rbind, lapply( fileList, function(X) {
data.frame(id = basename(X), tryCatch(read.table(X), error=function(e) NULL))}
))



Error in data.frame(id = basename(X), tryCatch(read.table(X), error =
function(e) NULL)) : arguments imply differing number of rows: 1, 0


Any suggestion on how to still merge the files and create a single data frame,even though some of the files don't have any rows(how can I just ignore them) ?

Answer

Use data.table Load the files with fread Bind all the data.tables with rbindlist I'll add code when you add a minimal reproducible example

library(data.table)
files = list.files(dir, pattern='.txt')
dtList = lapply(files, FUN=fread)
dt = rbindlist(dtList, use.names=TRUE)