Search code examples
rexport-to-csv

How to export csv with title above headers in r


I have a csv-file that looks like this:

enter image description here

In order for the file to work with an annoying third-party application it's absolutely vital that it looks like this instead, with at title above the variable headings:

enter image description here

That is to say like this if we edit the file with notepad:

enter image description here

Is there a way to do this in R?


Solution

  • 1) from a data.frame

    df_formatted <- rbind(c("title", rep(NA, ncol(df) - 1)), names(df), df)
    
    readr::write_csv2(df_formatted, "test.csv", col_names = FALSE, na = "")
    

    some sample data

    df <- data.frame(col1 = letters[1:3], col2 = 1:3, col3 = 2:4, col4 = 3:5)
    

    2) adding to an existing csv file

    fileConn <- file("test.csv")
    writeLines(c("title;;;", readLines(fileConn)), fileConn)
    close(fileConn)
    

    "in notepad"

    title;;;
    col1;col2;col3;col4
    a;1;2;3
    b;2;3;4
    c;3;4;5