[R] How to append to a data.frame?
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Dec 9 11:58:21 CET 2003
David Kreil <kreil at ebi.ac.uk> writes:
> Ok, how can I both allocate storage and specify column names in a data.frame
> call, please? Apologies if I'm being slow here.
It gets a little tricky. I'd try something along the lines of
data.frame(age=as.numeric(NA),sex=factor(NA,levels=c("m","f")))[rep(1,20),]
or
data.frame(age=0,sex=factor("m",levels=c("m","f")))[rep(NA,20),]
and of course the brute force way is
data.frame(age=rep(as.numeric(NA),20),
sex=factor(rep(NA,20),levels=c("m","f"))
)
Also,
(a) there's no idea in ensuring that you're filling with NA if they
are all going to be changed anyway, and
(b) recycling works so that you only need to specify the length of one
variable, so
data.frame(age=numeric(20), sex=factor("",levels=c("m","f")) )
works too.
Extending a data frame can be as simple as
mydata <- mydata[1:newlength,]
(plus fixup of row names later on).
> With many thanks again,
>
> David.
>
> > > Yes, once I've named the first column, I can add further ones by saying
> > > d[c("x","y","z")]=NA or such. I was just wondering whether that was the way to
> > > do it or whether there was a more elegant approach. Preallocation was the
> > > critical clue I needed.
> >
> > Use an initial data.frame call naming all the columns.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list