[R] R loop within a loop

saliluna saliluna at gmail.com
Wed Oct 12 15:37:32 CEST 2011


Hi,

I'm working on a loop function for a large dataset which contains 1000
different groups. I would like to reconstruct the order of events within
each group by using a loop function in R. (Currently the order of events are
based on the ascending order of prev_event within the group)


A demo data frame:

event       prev_event   group
845          0               5360
926          153            5360
993          234            5360
234          845            5360
848          926            5360
153          993            5360
234          0               8765
968          234            8765
545          968            8765
625          111            3334
744          181            3334
181          227            3334
713          625            3334
227          713            3334
913          0               2329
372          119            2329
719          189            2329
119          324            2329
761          355            2329
890          372            2329
266          719            2329
324          761            2329
189          890            2329
355          913            2329


Below is what I have written:

ordering <- vector("list", length(unique(mydata$group)))
for (j in 1:length(unique(mydata$group))){
group.j <- mydata[mydata$group == unique(mydata$group)[j], ]
ordering.j <- c()
ordering.j[1] <- ifelse(group.j[1, ]$prev_event == 0, group.j[1, ]$event,
group.j[1, ]$prev_event)
for (i in 2:nrow(group.j)){
ordering.j[i] <- group.j[group.j$prev_event == ordering.j[i-1], ]$event}
ordering[j] <- ordering.j}
ordering

What I got is:
Error in ordering.j[i] <- group.j[group.j$prev_event == ordering.j[i -  : 
  replacement has length zero
> ordering
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL


However, when I accidentally put a typo in the loop function, instead of
ordering.j[i] <- group.j[group.j$prev_event == ordering.j[i-1], ]$event},
I put
ordering.j[i] <- group.j[group.j$prev_event == ordering.j[i-1],
]$prev_event},
The output is a list of 1000 entries, each with the first event within the
group, and I received the following warning messages:
[[1]]
[1] 1.000680e+17

[[2]]
[1] 1.001390e+17

[[3]]
[1] 1.001450e+17

49: In ordering[j] <- ordering.j :
  number of items to replace is not a multiple of replacement length
50: In ordering.j[i] <- group.j[group.j$prev_event ==  ... :
  number of items to replace is not a multiple of replacement length


Why is this happening, and how can I fix it? Any pointer will be greatly
appreciated!

--
View this message in context: http://r.789695.n4.nabble.com/R-loop-within-a-loop-tp3898001p3898001.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list