[R] add repeated rows in data frame (without a loop)

Peter Ehlers ehlers at ucalgary.ca
Wed Feb 23 02:40:17 CET 2011


On 2011-02-22 14:48, Nicolas Gutierrez wrote:
> Hi All,
>
> I have a data frame "pop":
>
>   >     id  xloc  yloc  size
>   >  1  1	  10	12    95
>   >  2  2    11	10    81
>
> And I want to add the vector "rec" to the data frame "n" times (without
> using a loop):
>
>   >  rec=c(3, 5, 5, 10)
>   >  n=2
>
> The result I want:
>
>   >     id  xloc  yloc size
>   >  1  1	  10	12   95
>   >  2  2    11	10   81
>   >  3  3	  5	5    10
>   >  4  3    5     5    10		
>
> I know I can use pop=rbind(pop, rec) to add the vector "rec" once. What
> about adding the same vector "n" times without a for loop?  Any hints?

Try this:

  popm <- as.matrix(pop)
  recm <- matrix(rep(rec, n), nr=n, byrow=TRUE)
  newpop <- data.frame(rbind(popm, recm))

Peter Ehlers

>
> THANKS!
>
> Nico
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list