[R] Adding values to the end of a vector?

John Fox jfox at mcmaster.ca
Tue Jan 4 15:03:04 CET 2005


Dear Dan,

The following also works:

> x <- numeric(0)
> for (i in 1:5) x[i] <- i
> x
[1] 1 2 3 4 5

It's worth noting, however, that extending a vector in this manner can be
very inefficient for large vectors, since the vector is recopied each time.
If you can anticipate the number of elements (or place an upper bound on
it), then it's better to do something like

> x <- numeric(5)
> for (i in 1:5) x[i] <- i

I hope this helps,
 John

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox 
-------------------------------- 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Liaw, Andy
> Sent: Tuesday, January 04, 2005 8:51 AM
> To: 'Dan Bolser'; R mailing list
> Subject: RE: [R] Adding values to the end of a vector?
> 
> Is this what you're looking for?
> 
> > x <- numeric(0)
> > for (i in 1:5) x <- append(x, i)
> > x
> [1] 1 2 3 4 5
> 
> Andy
> 
> 
> > From: Dan Bolser
> > 
> > I want to add values onto the end of a vector, for example...
> > 
> > x <- vector
> > 
> > for (i in 1:5){
> >   add_to_end_of_vector(i,x)
> > }
> > 
> > I just cant find the answer to this question!
> > 
> > 
> > Sorry for such a basic question, I tried...
> > 
> > x <- c()
> > 
> > for (i in 1:5) x[length(x)] <- i
> > 
> > but it didn't work.
> > 
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide! 
> > http://www.R-project.org/posting-guide.html
> > 
> >
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html




More information about the R-help mailing list