r - Assocating Excel file name with dplyr::bind_rows .id -
i have 50-60 excel workbooks sitting in directory. these excel files , large same. there 2 work sheets, 1 instructions, same tidy data across sheets. columns/vars through j data want extract i'm willing read data.frame. data go out far through n cols.
i'm writing script extract of raw data , far good. part of script uses standard approach of list.files build 'df' of file names. then, use 'lapply' read of excel files list. here comes rub.
i want use dplyr::bind_rows (but open other suggestions) bind of rows since same , share same headers. works fantastic in proof of concept. when use .id argument of dplyr::bind_rows on it, 1 through j id var, corresponds data.frame position within list.
files.list <- list.files(pattern='*.xlsx') # list file names in directory df.list <- lapply(files.list, read_excel) # read excel list of dfs df <- bind_rows(df.list, .id = "id") # bind rows of dfs
is possible actual file name opposed position in list data.frame read? if so, how that?
try rename list of data frames file names using setnames
; ?bind_rows
: .id labels taken named arguments bind_rows(). when list of data frames supplied, labels taken names of list. if no names found numeric sequence used instead.
files.list <- list.files(pattern='*.xlsx') df.list <- setnames(lapply(files.list, read_excel), files.list) df <- bind_rows(df.list, .id = "id")
Comments
Post a Comment