What is the best way to read a file into R when the header has two necessary lines for the header?
This happens to me all the time, as people often use one line for
A slightly different explained step by step approach:
Read only the first two lines of the files as data (without headers):
headers <- read.table("data.txt", nrows=2, header=FALSE)
Create the headers names with the two (or more) first rows, sappy allows to make operations over the columns (in this case paste) - read more about sapply here :
headers_names <- sapply(headers,paste,collapse="_")
Read the data of the files (skipping the first 2 rows):
data <- read.csv(file="data.txt", skip = 2, header=FALSE)
And assign the headers of step two to the data:
names(data) <- headers_names
The advantage is that you would have clear control of the the parameters of read.table (such as sep for commas, and stringAsFactors - for both the headers and the data)