[R] converting a for loop into a foreach loop
kalee
kathryn.lee1 at students.mq.edu.au
Thu Jan 19 11:23:47 CET 2012
Dear all,
Just wondering if someone could help me out converting my code from a for()
loop into a foreach() loop or using one of the apply() function. I have a
very large dataset and so I'm hoping to make use of a parallel backend to
speed up the processing time. I'm having trouble getting selecting three
variables in the dataset to use in the foreach() loops. My for() loop code
is:
library(foreach)
library(multicore)
library(doMC)
registerDoMC()
> str(data)
'data.frame': 958 obs. of 13 variables:
$ Date.Time: Factor w/ 260 levels "03/07/09 00:00",..: 1 2 2 2 3 3 3 3 3 3
...
$ ID : int 3 1 3 7 1 3 7 8 10 12 ...
$ X : num 151 151 151 151 151 ...
$ Y : num -33.9 -33.9 -33.9 -33.9 -33.9 ...
$ Z : num 8 8 8 12 8 8 10 8 8 4 ...
$ breeding : int 1 1 1 1 1 1 1 1 1 1 ...
$ hour : int 0 0 0 0 0 0 0 0 0 0 ...
$ sex : Factor w/ 4 levels "","F","M","U": 3 4 3 4 4 3 4 3 2 4 ...
$ sex.code : int 1 3 1 3 3 1 3 1 2 3 ...
$ day : int 39997 39997 39997 39997 39997 39997 39997 39997 39997
39997 ...
$ hour1 : int 24 24 24 24 24 24 24 24 24 24 ...
$ X1 : num 1765688 1765492 1765492 1765637 1765383 ...
$ Y1 : num -3834667 -3834964 -3834964 -3834786 -3834990 ...
for (i in 1:15) {
x = data[data$ID == i, 1:10]
for (j in 1:length(x$day)) {
y = x[x$day == j, 1:10]
for (k in 1:length(y$hour1)) {
z = y[y$hour1 == k, 1:10]
H.scv <- Hscv(z, pilot = "unconstr")
KDE <- kde(z, H=H.scv, approx.cont=TRUE)
str(KDE)
head(KDE)
write.csv(KDE, file = paste("KDE",i j k,".csv"), row.names=T)
}
}
}
The foreach code I've tried (unsuccessfully) is:
x <- foreach(a = data[, 'ID'], .combine = "rbind") %:% foreach(b = data[ ,
'day'], .combine = "cbind") %:% foreach[c = data['hour1'], .combine
="cbind"] %dopar% {
H.scv <- Hscv((a,b,c), pilot = "unconstr")
KDE <- kde((a,b,c), H=H.scv, approx.cont=TRUE)
str(KDE)
head(KDE)
write.csv(KDE, file = paste("KDE",i,".csv"), row.names=T)
}
Many thanks for any help.
--
View this message in context: http://r.789695.n4.nabble.com/converting-a-for-loop-into-a-foreach-loop-tp4309646p4309646.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list