R losing a column when writing to csv

53 Views Asked by At

I download some stock data from yahoo. When I save this as a csv the first column (containing the dates) is lost. Any thoughts?

library (tidyverse)
library(forecast)
ftse <- getSymbols('^FTSE', auto.assign=FALSE, from = '2013-01-01', src= 'yahoo')
na.fill(ftse, "extend")
ftse_df <- as.data.frame (ftse)
ftse_df
colnames(ftse_df)<- c("open", "high", "low", "close", "volume", "adjusted")
ftse_df
write_csv(ftse_df,"C:/Users/xxx/ftse.csv")

Thanks,

Kevin

3

There are 3 best solutions below

0
Beatrice On

when you press Ctrl+Enter to visualise "ftse_df" do you see the first column? If not, there should be a problem above.

If you see the correct dataset, you can try this:

write_csv(ftse_df,"C:/Users/xxx/ftse.csv", row.names= TRUE)

Hope it will work!

Cheers, Beatrice

0
Kevin A On

Using write.csv solves this - opening the csv file shows the date column in place.

Thanks all.

2
G. Grothendieck On

No need to convert to data.frame or to write out the entire path. Use write.zoo and ~ like this where it is assumed that on your system path.expand("~") is "C:\\Users\\xxx\\Documents"

library(quantmod)

ftse <- getSymbols('^FTSE', auto.assign=FALSE, from = '2013-01-01')
write.zoo(ftse, "~/../ftse.csv", quote = FALSE, sep = ",",
  col.names = c("date", "open", "high", "low", "close", "volume", "adjusted"))

Check the file

readLines("~/../ftse.csv", n = 3)
## [1] "date,open,high,low,close,volume,adjusted"                                                               
## [2] "2013-01-02,5897.7998046875,6044.60009765625,5897.7998046875,6027.39990234375,652659400,6027.39990234375"
## [3] "2013-01-03,6027.39990234375,6051.2998046875,6016.7998046875,6047.2998046875,470665900,6047.2998046875"