[R] generating new data with for loop

Ben Bolker bolker at ufl.edu
Wed Jun 10 00:48:33 CEST 2009




Bugzilla from gordon.holtslander at usask.ca wrote:
> 
> I'm new at R ...
> I've not done for loops in R - so this is very new to me.
> 
> One of our students has a data frame that contains two columns data
> 
> 1. unixtime time of an event (in unix time - #of seconds)
> 2. duration of event in seconds.
> 
> We need to create new data - the unixtime (seconds) that these events 
> occurred.
> 
> We want to create a for loop  (or nested for loops) that goes through the 
> first column, and then creates a new unixtime value for each second of 
> duration for that event
> 
> In a single row of data -
> if the duration was three seconds one iteration of this loop should create 
> these values
> 
> unixtime
> unixtime = unixtime +1
> unixtime = unixtime +1
> unixtime = unixtime +1
> 
> I need these four data values (and all the successive data values created
> by 
> the loop(s)) saved into a new dataframe
> 
> How do I get R to create a new data object and add data to it on each 
> interation of the for loop.
> 
> My test for loops only save the data from last iteration of the loop.
> 
> Am I missing something really simple?
> 
> Any recommended reference on loop and control structures in R?
> 
> Thanks,
> 

Hard to see what you tried to do, so hard to correct it.

## "data"
d = data.frame(unixtime=5:10,duration=3:8)

## method 1 (magic)
d2 = data.frame(basetime=unlist(apply(d,1,function(x)
             {rep(x["unixtime"],1+x["duration"])})),
           time=unlist(apply(d,1,function(x)
{x["unixtime"]+0:x["duration"]})))

## method 2 (straightforward)
time <- numeric(sum(d$duration)+nrow(d))
count <- 0
for (i in 1:nrow(d)) {
  dur <- d$duration[i]
  time[(count+1):(count+dur+1)] <- d$unixtime[i]+0:dur
  count <- count+dur+1
}

## method 3 (slowest but simplest)
time <- numeric(0)
for (i in 1:nrow(d)) {
  dur <- d$duration[i]
  time <- c(time,d$unixtime[i]+0:dur)
}


-- 
View this message in context: http://www.nabble.com/generating-new-data-with-for-loop-tp23951415p23952650.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list