Reputation: 1047
I have this data in a CSV:
Date ALICORC1 ALT ATACOBC1 AUSTRAC1 CONTINC1 BVN DNT
40886 5.8 0.1 0.9 0.28 5.45 38.2 1.11
40889 5.8 0.1 0.88 0.28 5.37 37.7 1.04
40890 5.8 0.09 0.87 0.27 5.33 37.4 0.99
40891 5.7 0.1 0.85 0.27 5.3 37.5 0.91
These are stock closing prices from the Peruvian Stock Market, and I want to convert them to xts so I can find the optimal portfolio and other stuff, but I can't find the way to convert this CSV to xts. I've checked out the answer to many of the questions here but none of them worked.
Some of the errors I've got are:
Can anybody help me?
Upvotes: 2
Views: 8411
Reputation: 269644
csv stands for comma-separated-values so the layout shown in the question is not csv. We will assume that the data really is in csv form and not in the form shown the question. If it truly is in the form shown in the question rather than csv then omit the sep=","
argument in read.zoo
below. Also if there are other deviations you may need to modify the arguments further. See ?read.zoo
and the Reading Data in Zoo vignette in the zoo package.
Here we use read.zoo
in the zoo package to read in the data as a zoo object, z
, and then we convert it to xts, x
.
See R News 4/1 which specifically treats date handling of Excel dates noting that we may need to modify the code below slightly if the Mac version of Excel is being used (as described there in the reference).
library(xts) # this also loads zoo which has read.zoo
toDate <- function(x) as.Date(x, origin = "1899-12-30")
z <- read.zoo("myfile.csv", header = TRUE, sep = ",", FUN = toDate)
x <- as.xts(z)
zoo now has read.csv.zoo so the read.zoo line could be written:
z <- read.csv.zoo("myfile.csv", FUN = toDate)
Upvotes: 6