Home > Software design >  r lapply map_dfr id = "filename" not working
r lapply map_dfr id = "filename" not working

Time:12-18

I am combining 44 excel files into 1 df. I want to set an id col with the file name from each of the excel files so i can identify in final df.

file.list <- list.files(pattern='*.xlsx', recursive = TRUE)

df.list.add <- lapply(file.list, read_excel,"Additions")
 
all_additions <- map_dfr(df.list.add, ~.x %>% 
  mutate(across(everything(), as.character)), .id = "filename")

In all_additions the filename returned is numeric location in list of files rather than file name. It was working earlier. Do you know how I can fix this so that the id will be file name?

CodePudding user response:

lapply transfers names (from file.list) when they exist and numbers otherwise. Use setNames(nm=); the first argument (object=) is typically the object itself and the second argument (nm=) is the names to apply, but if object= is not provided, then it is effectively the same as setNames(obj, nm=obj).

df.list.add <- lapply(setNames(nm=file.list), read_excel,"Additions")
  • Related