[R] Replicating Rows

Tony Plate tplate at acm.org
Thu May 8 19:50:59 CEST 2008


Another way is using straightforward indexing:

 > x <- cbind(trips=c(1,3,2), y=1:3, z=4:6)
 > x
      trips y z
[1,]     1 1 4
[2,]     3 2 5
[3,]     2 3 6
 > # generate row indices with the appropriate
 > # number of repeats
 > ii <- rep(seq(len=nrow(x)), x[,1])
[1] 1 2 2 2 3 3
 > # use these indices to select data rows
 > x[ii, -1]
      y z
[1,] 1 4
[2,] 2 5
[3,] 2 5
[4,] 2 5
[5,] 3 6
[6,] 3 6
 >

Jorge Ivan Velez wrote:
> Hi Marion,
> 
> Try this:
> 
> set.seed(123)
> mydf=data.frame(trips=rpois(10,5), matrix(rnorm(10*5),ncol=5))
> mydf
> sapply(mydf[,-1],rep,mydf[,1])
> 
> 
> HTH,
> 
> Jorge
> 
> 
> On Wed, May 7, 2008 at 11:41 PM, <mwittmann at bren.ucsb.edu> wrote:
> 
>>
>> Hi,
>>
>>  I have a data matrix in which there are 1000 rows by 30 columns. The
>> first
>> column of each row is a numeric indicating the number of trips taken to a
>> particular location with location attributes in the following column
>> entries for
>> that row.
>>
>> I want to repeat each row based on the number of trips taken (as indicated
>> by
>> the number in the first column)...i.e., if 1,1 indicates 4 trips, I want
>> to
>> replicate row 1 four times, and do this for each entry of column 1.
>>
>> I have played with rep command with little luck. Can anyone help? This is
>> probably very simple.
>>
>> Thank you,
>>
>> mw
>>
>>
>> Marion Wittmann, Ph.D. candidate
>> Environmental Science and Management
>> University of California
>> Santa Barbara, CA 93106-5131
>>
>> ______________________________________________
>> 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.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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