[R] cbind(NULL,zoo.object)?
Ajay Shah
ajayshah at mayin.org
Sun Mar 15 07:54:24 CET 2009
Folks,
I often build up R objects starting from NULL and then repeatedly
using rbind() or cbind(). This yields code like:
a <- NULL
for () {
onerow <- craft one more row
a <- rbind(a, onerow)
}
This works because rbind() and cbind() are forgiving when presented
with a NULL arg: they act like nothing happened, and you get
all.equal(x,rbind(NULL,x)) or all.equal(x,cbind(NULL,x)).
This same idea is useful in building up a zoo matrix, by cbinding one
column after another. I find this quite elegant, though I'm conscious
that it leads to a lot of expensive memory management.
This approach breaks around zoo because cbind(NULL,z) doesn't work:
> tmp <- structure(c(2.65917577210146, 1.17190441781228, 0.838363890267146,
-0.293979039853021, -0.132437820890186,
0.262002985990861, 2.16601367541420,
0.375245019370496, 0.0108451048014047,
1.56555812127923), index = structure(c(12509,
12510, 12513, 12514, 12515, 12516, 12521, 12524, 12528,
12529), class = "Date"), class = "zoo")
> tmp
2004-04-01 2004-04-02 2004-04-05 2004-04-06 2004-04-07 2004-04-08
2.65917577 1.17190442 0.83836389 -0.29397904 -0.13243782 0.26200299
2004-04-13 2004-04-16 2004-04-20 2004-04-21
2.16601368 0.37524502 0.01084510 1.56555812
> cbind(NULL,tmp)
12509 12510 12513 12514 12515 12516
2.65917577 1.17190442 0.83836389 -0.29397904 -0.13243782 0.26200299
12521 12524 12528 12529
2.16601368 0.37524502 0.01084510 1.56555812
Warning message:
In merge.zoo(..., all = all, fill = fill, suffixes = suffixes, retclass = "zoo") :
Index vectors are of different classes: integer Date
Is there an easy workaround; or am I deeply confused; is there a way
out? :-)
--
Ajay Shah http://www.mayin.org/ajayshah
ajayshah at mayin.org http://ajayshahblog.blogspot.com
<*(:-? - wizard who doesn't know the answer.
More information about the R-help
mailing list