R - forcing each file's data into a different column during bulk upload

Viewed 18

I am doing a bulk import with the following code

dat <- dir_ls(regexp = "*.csv") %>%
  map_df(read_csv2,
         col_types = cols(.default=col_character() ) )

Some files have simillar headings and dat has some columns with stacked data (when a couple of csv have the same headings).

To make things uniform, it would be convenient to force the data of each file to be launched in a different column (and to avoid columns with data from 2 or more different files, although they have same heading). Is it possible to achieve this with some addition to the previous code?

Thank you.

1 Answers

You could first retrieve the files into a list

    mylist = lapply(dir_ls(regexp = "*.csv"), read_csv2,
             col_types = cols(.default=col_character() ))

Then cbind them together

as.data.frame(mylist)

This will ensure unique names.

Related