Search code examples
rtext-files

Dataframe to text file with column names


I have a dataframe with a larger data and columns than shown below:

df <- data.frame(A = c(1,2,3),
                 B = c("DD", "EE", "FF"))

I'd like to convert this data frame to a text file, but the content of this file should be like this:

A 1  
B DD  
  
A 2  
B EE  
  
A 3  
B FF  

Solution

  • You can use mapply to paste the data in required order and use cat to write it to text file.

    cat(paste0(c(t(mapply(paste, names(df), df))), 
                 collapse = '\n'), file = 'result.txt')