Reputation: 2654
I am trying to convert data.frame objects to zoo (zoo package) objects. The first step in doing that is to convert a date column in my data (df) into Date class using as.Date
with the format D/M/Y. The data looks like:
Date Return
1986-02-03 0.10
1986-02-04 0.15
1986-02-05 0.16
1986-02-06 0.18
When using the following code:
df.data <- as.Date(df$Date)
it converts to the class but dates are on Y-M-D format. When using the following code
df.data <- as.Date(df$Date, format = "%d/%m/%y")
it give NA of all values. Where is the problem?
Sys: Mavericks 64bit
Upvotes: 2
Views: 4371
Reputation: 269654
Use read.zoo
:
z <- read.zoo(DF)
Note: We assumed DF
is:
DF <- data.frame(Date = c("1986-02-03", "1986-02-04", "1986-02-05", "1986-02-06"),
Return = c(0.1, 0.15, 0.16, 0.18))
Upvotes: 4
Reputation: 887173
df <- structure(list(Date = c("1986-02-03", "1986-02-04", "1986-02-05",
"1986-02-06"), Return = c(0.1, 0.15, 0.16, 0.18)), .Names = c("Date",
"Return"), class = "data.frame", row.names = c(NA, -4L))
library(zoo)
zoo(df[,2], format(as.Date(df$Date), "%d/%m/%y"))
#03/02/86 04/02/86 05/02/86 06/02/86
# 0.10 0.15 0.16 0.18
zoo(df[,2],as.Date(df$Date))
#1986-02-03 1986-02-04 1986-02-05 1986-02-06
# 0.10 0.15 0.16 0.18
Upvotes: 1