Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write dates to Excel properly from R

Tags:

r

When I write dataframe to the file it considers all columns as characters including the date column.

options(xlsx.date.format = "yyyy-mm-dd")
write.xlsx(data, excel_filename, sheetName = "Data")

enter image description here

How can I write data to xlsx file such that when I work with this column it considered as date by default?

Solution: Turns the class of the column was character. After conversion with as.Date everything is saved properly.

like image 822
Sergey Ivanov Avatar asked Aug 15 '16 18:08

Sergey Ivanov


People also ask

How do I write R results in Excel?

Write data from R to Excel files using xlsx package: write. xlsx(my_data, file = “result. xlsx”, sheetName = “my_data”, append = FALSE).

How do I write a date in R?

The standard date format is “YYYY-MM-DD.” To get the current system date, we can use the Sys. Date() function. Sys.


2 Answers

The reference manual for xlsx explains it very clearly with example. Below is a slight modified Source: https://cran.r-project.org/web/packages/xlsx/xlsx.pdf I think, you were following the same approach. working with workbook saves the format of the date.

wb <- createWorkbook(type="xlsx")
 sheet <- createSheet(wb, sheetName="addDataFrame1")
 data <- data.frame(date=seq(as.Date("1999-01-01"), by="1 year", length.out=10))
 addDataFrame(data, sheet, startRow = 1, startColumn=1)
 # to change the default date format use something like this
 options(xlsx.date.format="dd MMM, yyyy")
 # Don't forget to save the workbook ...
 saveWorkbook(wb, "Path/test.xlsx") # your path to the excel sheet
like image 181
user5249203 Avatar answered Sep 20 '22 06:09

user5249203


You may try using lubridate or chron libraries for this task. However, I do not think your issue is coming from R but more with how excel is reading it. In your question, is the image you show of how you want it to look or how it currently looks? In any case, when using chron for example, you can say

 format.Date(dates, "%Y/%m/%d")
like image 26
user5727 Avatar answered Sep 20 '22 06:09

user5727