Reputation: 2652
I have a zoo object z
with 10 rows and 2 columns as follow:
Date Return
1986-01 0.00308215260513781
1986-02 0.00305355599484584
. .
. .
. .
1986-10 0.00349830477430457
I need a new
zoo object that contains the z
object along with a new column X
from data frame df
. The desired output should look like:
Date Return X
1986-01 0.00308215260513781 11
1986-02 0.00305355599484584 12
. . .
. . .
. . .
1986-10 0.00349830477430457 20
I used the following code:
new= merge(z , df$X)
However, it gives the results not as desired but with each value in X
assigned to each row of z
. The new
object now has 100 rows. It also removed the date column from the zoo object. Could not find where is the problem.
For a reproducible example:
# get the z object
structure(c(NA, 0.00308215260513781, 0.00305355599484584, 0.00166059811703964,
-0.00511749445720536, -0.00145300480100395, -0.00171675339332211,
-0.00335452754121814, 0.000189812976282344, 0.00349830477430457
), .Dim = 10L, .Dimnames = list(c("1986-01", "1986-02", "1986-03",
"1986-04", "1986-05", "1986-06", "1986-07", "1986-08", "1986-09",
"1986-10")))
# get the df data frame
structure(list(a = 1:10, X = 11:20), .Names = c("a", "X"), row.names = c(NA,
-10L), class = "data.frame")
Upvotes: 2
Views: 3782
Reputation: 270438
The problem is that z
in the question is not a zoo object.
Either of these will create a zoo object with z
as the first column and df$X
as the second:
read.zoo(data.frame(rownames(z), Return = z, X = df$X), FUN = as.yearmon)
merge(Return = zoo(z, as.yearmon(rownames(z))), X = df$X)
giving:
Return X
Jan 1986 NA 11
Feb 1986 0.003082153 12
Mar 1986 0.003053556 13
Apr 1986 0.001660598 14
May 1986 -0.005117494 15
Jun 1986 -0.001453005 16
Jul 1986 -0.001716753 17
Aug 1986 -0.003354528 18
Sep 1986 0.000189813 19
Oct 1986 0.003498305 20
Upvotes: 2