I would like to transform the following nested for loop
first <- c(1, 2, 3)
second <- c(1, 2, 3)
dummy = matrix(double(), len(first), len(second))
c <- list()
c$sum <- dummy
c$times <- dummy
for (i in 1:len(first)) {
for (j in 1:len(second)) {
c$sum[i, j] <- first[i] + second[j]
c$times[i, j] <- first[i] * second[j]
}
}
c
into code using foreach and get the same list of matrices as a result. I tried many different things but the closest “result” is this:
x <- foreach(b = second, .combine = "cbind") %:% foreach(a = first, .combine = "c") %do% {
c <- list()
c$sum <- a+b
c$times <- a*b
out <- c
}
x
How to get this list of matrices right using foreach?
EDIT: One possibility is using a result and transform it after calling foreach:
res <- list()
res$sum <- x[rownames(x)=="sum", ]
rownames(res$sum) <- NULL
colnames(res$sum) <- NULL
res$times <- x[rownames(x)=="times", ]
rownames(res$times) <- NULL
colnames(res$times) <- NULL
res
How to “parametrize” foreach so there is no need to transform results?
You “just” have to provide the correct
.combinefunction.If you only have numbers, you can return an array rather than a list.
If you really need lists, writing the combining functions is much harder.
Instead, you can build a data.frame, and reshape it afterwards, if needed.