[R] reformat records one to several

jim holtman jholtman at gmail.com
Thu Sep 14 00:13:28 CEST 2006


Try this:

n <- 10  # create some sample data
x <- data.frame(date=1:n, t1=sample(0:3, n, TRUE), t2=sample(0:3, n, TRUE),
    t3=sample(0:3, n, TRUE))
x  # print data
result <- lapply(c('t1','t2','t3'), function(i){
    xsub <- x[rep(1:nrow(x), x[[i]]),]
    xsub$t1 <- xsub$t2 <- xsub$t3 <- 0
    xsub[[i]] <- 1
    xsub
})
do.call('rbind', result)  # result


On 9/13/06, Steven Van Wilgenburg <slv511 at mail.usask.ca> wrote:
> Hi,
>
> I am a new user of R and am still trying to figure out which statements
> do which functions and am looking for a jump start.
>
> I have a dataset where the data were collected as ten minute counts
> where the number of new individuals within a species was recorded as
> cohorts within 3 separate time intervals within the ten minute count
> persiod. Each row of data therefore follows a format like this:
>
>       Date    Time       Sample        Species t1 t2 t3
> June 5,2006 5:20 AM AUSFAKE01   OVEN    3  0  1
> etc.....
>
> I would like to reformat these data as if the counts recorded only
> individuals and not cohorts, so that the above would look as follows
>
>       Date    Time       Sample        Species t1 t2 t3
> June 5,2006 5:20 AM AUSFAKE01   OVEN    1  0  0
> June 5,2006 5:20 AM AUSFAKE01   OVEN    1  0  0
> June 5,2006 5:20 AM AUSFAKE01   OVEN    1  0  0
> June 5,2006 5:20 AM AUSFAKE01   OVEN    0  0  1
> etc.....
>
> I believe I could do this in SAS with IF, THEN and DO statements,
>
> e.g.
> if t1>0 then
>        do i=1 to t1
>                output Date,Time,Sample,Species,"1","0","0";
> if t2>0 then
>        do i=1 to t2
>                output Date,Time,Sample,Species,"0","1","0";
> if t3>0 then
>        do i=1 to t3
>                output Date,Time,Sample,Species,"0","0","1";
> end;
>
>
> Can anyone point me in the right direction? What is the similar
> statement to DO in R?
>
> Steve VW
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list