简体   繁体   中英

numbers stored as text when exporting to excel using package xlsx

I am working with R3.1.1, and the xlsx package. I also use the excel 2007 software. When I have a large data frame, the data gets exported to excel as text. I have tried using wb=set_optimization() without any luck. For example if I use this data frame:

size1<-rnorm(100,5000,2000)
size2<-rnorm(100,5000,2000)
size3<-rnorm(100,5000,2000)
name1<-paste("RNORM",seq(1,100,1), sep<-"")
fold1<-rnorm(100,4,2)
fold2<-rnorm(100,3,1)
fold3<-rnorm(100,2,0.5)
N1<-sample(18:36,100, replace <- TRUE)
df<-cbind(name1,N1,size1,size2,size3,fold1,fold2,fold3)

wb <- createWorkbook()
sheet.1 <- createSheet(wb, sheetName="test1")
sheet.2 <- createSheet(wb, sheetName="test2")
addDataFrame(df, sheet=sheet.1,  row.names=FALSE, startRow = 1, startColumn = 1)
addDataFrame(df, sheet=sheet.2,  row.names=FALSE, startRow = 1, startColumn = 1)
saveWorkbook(wb, "testing1.xlsx")

All of the numbers are stored in the excel workbook as text. How do I remove this coding to make the final file easier to read?

When you use cbind on a group of vectors it returns a matrix. Since a matrix is simply a two dimensional vector, all values must be the same type.

Since the name1 vector is a character vector, all the other vectors are also coerced to character to meet this constraint.

To get the intended result you can use data.frame instead:

df <- data.frame(name1, N1, size1, size2, size3, fold1, fold2, fold3)

wb <- createWorkbook()
sheet.1 <- createSheet(wb, sheetName = "test1")
sheet.2 <- createSheet(wb, sheetName = "test2")
addDataFrame(df, sheet = sheet.1,  row.names = FALSE, startRow = 1, startColumn = 1)
addDataFrame(df, sheet = sheet.2,  row.names = FALSE, startRow = 1, startColumn = 1)
saveWorkbook(wb, "testing1.xlsx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM