Q:

Add Additional Headers to a Dataframe

I am reading in a .csv file that has three relevant header rows. I'd like to read in the file, modify some of the variables, and export the .csv (keeping the same three header rows).
Var1, Var2, VarN
In, Lb, Yrs
Height, Weight, Age
5'8, 180, 40
...

I saved the first two header rows:
headers <- read.csv(filename, header=F, nrows=2, as.is=T)

I read in the rest of the data with a single header (skipping the first two rows I have just saved above):
df <- read.csv(filename, skip=2, header=T, as.is=T, stringsAsFactors = FALSE)

After making a number of modifications to the data, I'd like to add back in the two headers. Using rbind results in an error as the names don't match. The number of rows remains the same (no new rows were created). Thanks for any tips!

A:

#First write your headers to csv
write.table(x = mtcars[1:3,],
            file = "test.csv",
            col.names = TRUE,
            row.names = FALSE,
            sep = ",",
            append = FALSE)

#Then write your modified data
write.table(x = mtcars[-(1:3),] * 2000,
            file = "test.csv",
            col.names = FALSE,  #We've written this the first time
            row.names = FALSE,
            sep = ",",
            append = TRUE)      #add to an existing file

