rexcelopenxlsx

Automatically - "Convert numbers stored as text to numbers"


Lets consider this small example:

df1<- data.frame(A=c(1,NA,"pvalue",0.0003),B=c(0.5,7,"I destroy","numbers all day"),stringsAsFactors = T)

Write file:

openxlsx::write.xlsx(df1,"Test.xlsx")

In my resulting excel file, 1 and 7 are text cells. Excel has the "intuition" that they are numbers stored as text. I can convert them by hand.

How can I convert those "flagged" values automatically to numbers from inside R?

In the "What I want" I have by hand converted the TEXT into Numbers. It's an option behind the "green triangle" in the "What I get" Part (red arrows).

enter image description here

@Roland's comment: Rearranging as list does not work.

df1<- as.data.frame(cbind(A=list(1,NA_real_,"pvalue",0.0003),B=list(0.5,7,"I destroy","numbers all day")))
openxlsx::write.xlsx(df1,"Test2.xlsx")

Solution

  • I wrote a small piece of code following the suggestions of @Roland and @phiver. It starts with a tidy data.frame (to preserve the data type of each cell) and save values one by one:

    library(openxlsx)
    df1<- as.data.frame(cbind(A=list(1,NA_real_,"pvalue",0.0003),B=list(0.5,7,"I destroy","numbers all day")))
    
    wb <- createWorkbook()
    sheet.name <- 'test'
    addWorksheet(wb, sheet.name)
    
    for(i in seq_along(df1)){
        writeData(wb, sheet = sheet.name, names(df1)[i], startCol = i, startRow = 1)
        icol <- df1[[i]]
        for(j in seq_along(icol)){
            x <- icol[[j]]
            writeData(wb, sheet = sheet.name, x, startCol = i, startRow = j + 1)
        }
    }
    saveWorkbook(wb, file = "Test.xlsx")
    

    enter image description here

    Hope this works for your data.