Search code examples
rcsvformatr-xlsx

Formatting a XLSX file in R into a custom text blob


I want to read a xlsx file and I want to convert the data in the file into a long text string. I want to format this string in an intelligent manner, such as each row is contained in parentheses “()”, and keep the data in a comma separated value string. So for example if this was the xlsx file looked like this..

one,two,three
x,x,x
y,y,y
z,z,z

after formatting the string would look like

header(one,two,three)row(x,x,x)row(y,y,y)row(z,z,z)

How would you accomplish this task with R?

my first instinct was something like this… but I can’t figure it out..

library(xlsx)
sheet1 <- read.xlsx("run_info.xlsx",1)
paste("(",sheet1[1,],")")

Solution

  • This works for me:

    DF <- read.xlsx("run_info.xlsx",1)
    
    paste0("header(", paste(names(DF), collapse = ","), ")", 
           paste(paste0("row(", apply(DF, 1, paste, collapse = ","), ")"),
                 collapse = ""))
    # [1] "header(one,two,three)row(x,x,x)row(y,y,y)row(z,z,z)"