将列添加到动物园对象 [英] Adding column to zoo object

查看:22
本文介绍了将列添加到动物园对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 10 行 2 列的动物园对象 z 如下:

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

我需要一个 new 动物园对象,其中包含 z 对象以及来自数据框 dfX代码>.所需的输出应如下所示:

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

我使用了以下代码:

new= merge(z , df$X)

然而,它给出的结果并不如预期,而是将 X 中的每个值分配给 z 的每一行.new 对象现在有 100 行.它还从动物园对象中删除了日期列.找不到问题出在哪里.

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.

对于可重现的示例:

# 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")

推荐答案

问题是问题中的 z 不是动物园对象.

The problem is that z in the question is not a zoo object.

其中任何一个都将创建一个以 z 作为第一列和 df$X 作为第二列的动物园对象:

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)

给予:

               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

这篇关于将列添加到动物园对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆