0

I want to convert the dataset "co2" that comes in R to a CSV. My code is the following:

require(xts)
require(zoo)
co2_xts <- as.xts(co2)
write.zoo(co2_xts, file="demo.csv",sep=",")

This works fine. But the time index shows as, for example, "ene. 1959" (it is in spanish). I would like the index to take the format "%B %Y" if possible. If I use:

co2_xts <- as.xts(co2,dateFormat="%B %Y")

This throws an error:

Error in `as.%B %Y`(c(1959, 1959.08333333334, 1959.16666666668, 1959.25000000002,  : 
could not find function "as.%B %Y"

So how can I achieve what I want?

davidaap
  • 1,569
  • 1
  • 18
  • 43

2 Answers2

1

You can adjust the index format after you created the xts with the indexFormat function.

In this case:

indexFormat(co2_xts) <- "%B %Y" 

Note that this only changes the display format.

phiver
  • 23,048
  • 14
  • 44
  • 56
  • Thanks, this worked fine. However, when I use %B or %b the result is the same, it shows as "Jan 1959" instead of "January 1959". Why does this happen? – davidaap Oct 21 '19 at 15:15
  • 1
    this only formats the display, not the underlying values, they stay the same. So when you export it to csv it will be exported as Jan 1959. you might want to use indexClass(co2_xts) <- "Date". This will transform all the year mon values into 1959-01-01, etc. – phiver Oct 21 '19 at 16:42
0

Have you thought about the timetk package and saving the tibble?

require(timetk)
co2_tbl <- tk_tbl(co2, start = start(co2), freq = 12)

Then use the more generic write.csv, or one of the faster methods, e.g. fread::write_csv if a long file:

write.csv(co2_tbl, file="demo.csv", row.names=FALSE)
Tech Commodities
  • 1,884
  • 6
  • 13