[R] using contents of one column to direct addition of new rows indataframe

Peter Alspach Peter.Alspach at plantandfood.co.nz
Mon Nov 23 22:39:51 CET 2009


Tena koe Jessi

One solution:

> jessi
  ID Date Time
1 N1    2    3
2 N2    6    4
> Jessi <- jessi[rep(1:nrow(jessi), jessi[,3]),-3]
> Jessi
    ID Date
1   N1    2
1.1 N1    2
1.2 N1    2
2   N2    6
2.1 N2    6
2.2 N2    6
2.3 N2    6
> Jessi[,2] <- Jessi[,2]+unlist(apply(as.matrix(jessi[,3]), 1, seq))-1
> Jessi
    ID Date
1   N1    2
1.1 N1    3
1.2 N1    4
2   N2    6
2.1 N2    7
2.2 N2    8
2.3 N2    9

HTH ...

Peter Alspach

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Jessi Brown
> Sent: Tuesday, 24 November 2009 9:33 a.m.
> To: r-help at r-project.org
> Subject: [R] using contents of one column to direct addition 
> of new rows indataframe
> 
> Hello, R gurus. I've been trying to get R to do some data 
> manipulation for me, and so far have been stumped in figuring 
> out any elegant way to do so. Searches through the R-help 
> archive haven't helped, so now I'm trying plan B.
> 
> Suppose I have a dataframe that summarizes events that took 
> place between some interval of time in days, "Time." I want 
> to expand the dataframe to repeat each row the appropriate 
> number of days so that Time is now = 1 for each original 
> record. Actually, I really don't care if Time=1 is displayed 
> in the new dataframe, as it will no longer be relevant.
> 
> Also, I want to have R keep track of a time-variant variable, 
> Date, so that it advances along one day for each new row. 
> Here's an example of what the starting record would be like, 
> and what I'd like to end up
> with:
> 
> > foo.df <- data.frame(ID="N1", Date=2, Time=3) foo.df
>   ID Date Time
> 1 N1    2    3
> 
> # insert R wizardry here to get new.foo.df
> 
> >new.foo.df
> ID	Date	Time
> N1	2	1
> N1	3	1
> N1	4	1
> 
> 
> I know, or at least suspect, that there is a fairly 
> straightforward way of doing so with building some ugly loop. 
> But even after considering versions of "apply" and related 
> commands, I just can't figure it out. Any help would be 
> greatly appreciated.
> 
> cheers, Jessi Brown
> 
> University of Nevada, Reno
> 
> ______________________________________________
> 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