# How do I get a list of matrices as a result of a foreach?

I would like to convert the following nested loop to 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 the code using foreach and get the same list of matrices as a result. I've tried many different things, but the closest "result" is:

``````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 do I get this list of matrices correctly using foreach?

EDIT: One possibility is using the result and converting it after the foreach call:

``````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 "parameterize" foreach so there is no need to convert the results?

+3

source to share

You "just" have to provide the correct function `.combine`

. If you only have numbers, you can return an array, not a list.

``````library(foreach)
library(abind)
first <- 1:3
second <- 4:5
x <-
foreach(b = second, .combine = function(...) abind(..., along=3)) %:%
foreach(a = first,  .combine = rbind) %do% {
c( sum=a+b, times=a*b )
}
```

```

If you really want lists, writing union functions is much more difficult. Instead, you can create a data.frame file and then modify it if needed.

``````x <-
foreach(b = second, .combine = rbind) %:%
foreach(a = first,  .combine = rbind) %do% {
data.frame(a=a, b=b, sum=a+b, times=a*b )
}
library(reshape2)
list(
sum   = dcast(x, a ~ b, value.var="sum"  )[,-1],
times = dcast(x, a ~ b, value.var="times")[,-1]
)
```

```
+2

source

All Articles