loops - R loading multiple excel files and merge -
i have many excel files need load , merge single data frame.
the script below works! however, before merging files want paste each file name in new column.
library(gdata) library(tools) filelist <- list.files(pattern = "*\\.xlsx$") files = lapply(filelist, read.xls, header=true) new = reduce(function(...) merge(..., all=t), files) so added this:
files$source <- file_path_sans_ext(filelist) however, didn't work.
my desired output is:
col1 col2 col3 source(this column doesnt exist in excel) abc 1 2 filename1 def 3 4 filename2 how can achieve this?
try
library(tools) source <- file_path_sans_ext(filelist) files1 <- map(cbind, files, source=source) files1 #[[1]] # col1 col2 source #1 0.5365853 filname1 #2 0.4196231 filname1 #[[2]] # col1 col2 source #1 0.847460 filname2 #2 c 0.266022 filname2 #[[3]] # col1 col2 source #1 c -0.4664951 filname3 #2 c -0.8483700 filname3 data
set.seed(24) files <- lapply(1:3, function(i) data.frame(col1=sample(letters[1:3], 2, replace=true), col2=rnorm(2))) filelist <- paste0('filname', 1:3, '.txt')
Comments
Post a Comment