-1

Please help!
I have a .csv file with 4 columns: Date, VBLTX, FMAGX and SBUX. The three latter columns are adjusted closing prices of some stocks. And the date column are the months from Jan-1998 to Dec-2009. Here is the first couple or rows:

Date      |VBLTX      |FMAGX        |SBUX  
1/01/1998 |4.36       |44.38        |4.3  
1/02/1998 |4.34       |47.74        |4.66  
1/03/1998 |4.35       |47.74        |5.33

I am trying to read this into R as a zoo object that should look like this:

         |VBLTX      |FMAGX        |SBUX  
Jan 1998 |4.36       |44.38        |4.3  
Feb 1998 |4.34       |47.74        |4.66  
Mar 1998 |4.35       |47.74        |5.33

I have no idea how to make this work. I am currently using this line of code:

all_prices <- read.zoo("all_prices.csv", FUN = identity)

And this produces this zoo series:

         |V2         |V3           |V4  
Apr-00   |4.63       |73.15        |7.12  
Apr-01   |5.22       |63.05        |9.11  
Apr-02   |5.71       |53.88        |10.74

It appears to have sorted the csv file alphabetically rather than by date. Also if I scroll through the zoo series there is a row which is the column names from the csv file.

Any help would be appreciated

Thanks!

1 Answers1

2

If you have "no idea" how to use a command then read the help file for it carefully -- in this case ?read.zoo. Also there is a vignette that comes with zoo entirely devoted to read.zoo examples: vignette("zoo-read") . Also reviewing ?yearmon would be useful here.

Assuming that the input file is as shown reproducibly in the Note at the end and NOT as shown in the question it should NOT have a .csv extension since it is not a csv file; however, ignoring that we have the following.

header = TRUE says the first line is a header, FUN = as.yearmon says we want to convert the first column to a yearmon class time index and format specifies its format (using the percent codes defined in ?strptime).

library(zoo)

read.zoo("all_prices.csv", header = TRUE, FUN = as.yearmon, format = "%d/%m/%Y")

giving:

         VBLTX FMAGX SBUX
Jan 1998  4.36 44.38 4.30
Feb 1998  4.34 47.74 4.66
Mar 1998  4.35 47.74 5.33

Note

Lines <- "
Date      VBLTX      FMAGX        SBUX  
1/01/1998 4.36       44.38        4.3  
1/02/1998 4.34       47.74        4.66  
1/03/1998 4.35       47.74        5.33
"
cat(Lines, file = "all_prices.csv")
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341