user2479802 user2479802 - 1 month ago 8
R Question

Import multiple CSVs without headers into single R data frame

I'm attempting to import a large amount of CSV files with no headers into a single data frame in R using the following code, but it results in the error message "names do not match previous names". I'm guessing this function requires the data to have headers. What function can I use for this process that allows for importing data without headers?

filedir <- setwd("C:/test/")
file_names <- dir(filedir)
your_data_frame <- do.call(rbind,lapply(file_names,read.csv))

Answer

If at the moment your files have different headers, then I think we can use

do.call(rbind, lapply(file_names, read.csv, skip = 1, header = FALSE))

providing that all your files have equal number of columns and same data class. The skip = 1L ignores existing header in each file, while header = FALSE will automatically generates V1, V2, ..., as column names, consistent for all data frames.

But if your files have no headers, you just need to set

do.call(rbind, lapply(file_names, read.csv, header = FALSE))

Oh, as user20650 kindly reminded, you need the second option.

Comments