Reputation: 447
I'm reading and combining a large group of csv tables into R but before merging them all I'll like to create a column with the name of the file where those specific set of rows belong.
Here is an example of the code I wrote to read the list of files:
archivos <- list.files("proyecciones", full.names = T)
#proyecciones is the folder where all the csv files are located.
tbl <- lapply(archivos, read.table, sep="", head = T) %>% bind_rows()
As you can see I already have the names of the files in "archivos" but still haven't been able to figure it out how to put it into the lapply command.
Thanks!
Upvotes: 1
Views: 1051
Reputation: 886938
We need to use the .id
in bind_rows
lapply(archivos, read.table, sep="", header = TRUE) %>%
set_names(archivos) %>%
bind_rows(.id = 'grp')
A more tidyverse syntax would be
library(tidyverse)
map(archivos, read.table, sep='', header = TRUE) %>%
setnames(archivos) %>%
bind_rows(.id = 'grp')
Upvotes: 1