How to avoid writing a row.names column when saving a data.frame using the xlsx package

Davi Moreira picture Davi Moreira · Aug 25, 2012 · Viewed 43.8k times · Source

I have a data frame like this one below and I really want to remove the row names when I export it to a excel file using the xlsx package.

bd <- data.frame(id = 1:200, A = c(rep("One", 100), rep("Two", 100)), 
             B = c(rep(1,50), rep(0, 50), rep(1, 50), rep(0, 50)))

I have already tried to use the command below, but it keep them in the first column of the excel file.

bd <- data.frame(id = 1:200, A = c(rep("One", 100), rep("Two", 100)), 
             B = c(rep(1,50), rep(0, 50), rep(1, 50), rep(0, 50)), row.names=NULL)

Is there any way to do this?

Answer

Andy picture Andy · Aug 25, 2012

Set the rownames to NULL to remove them:

rownames(bd) <- NULL

Also, from xlsx documentation:

write.xlsx(x, file, sheetName="Sheet1",
           col.names=TRUE, row.names=TRUE, append=FALSE)

Set row.names to FALSE to avoid the first column being row names.