Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using write_xlsx in R

Tags:

r

writexl

I'm using the write_xlsx command to export data from R to excel,

Here is the data frame that I have,

 >df
     X1
 A   76
 B   78
 C   10

Using ,

write_xlsx(df, "../mydata.xlsx")

gives the following output in excel,

 >df

1  76
2  78
3  10

The column names appear in the xlsx file but the index of each row isn't printed. Is there any way to print the row index in the excel file?

like image 849
Natasha Avatar asked Aug 23 '18 11:08

Natasha


1 Answers

If you want to use the write_xlsx() function (from the writexl package), then you can simply make the row names into the first column of the data frame with the cbind() function:

mtcars1 <- cbind(" "=rownames(mtcars), mtcars)
writexl::write_xlsx(mtcars1, "mtcars1.xlsx")

I've used " "= so the header of column A will appear blank (it will be a space). It can be easily swapped to some other name (e.g., Model=) if desired.

If you have a list of data frames, this can be easily adapted to create a multiple sheet file:

mtcars2 <- list(Sheet1=mtcars[1:5, ], Sheet2=mtcars[6:10, ])
mtcars2_1 <- lapply(mtcars2, function(x) cbind(" "=rownames(x), x))
writexl::write_xlsx(mtcars2_1, "mtcars2.xlsx")
like image 74
Tim Bainbridge Avatar answered Sep 19 '22 00:09

Tim Bainbridge