Reputation: 643
Suppose we have the following data set named data2
.
id v1 v2
1 5 0.5
1 4 0.5
1 6 0.5
2 2 0.2
2 3 0.2
2 7 0.2
2 8 0.2
The following code:
library(doParallel)
un_id <- unique(data2$id)
out <- vector('list', length(un_id))
names(out) <- un_id
registerDoParallel(cl <- makeCluster(length(un_id)))
for(id1 in un_id) {
subdat <- subset(data2, id == id1)
out[[id1]] <- foreach(i = nrow(subdat)) %dopar% {
a <- matrix(nrow = nrow(subdat), ncol=2)
for (j in 1:nrow(subdat)) {
for (k in 1:2) {
a[j,k] <- j*k
}
}
a
}
}
stopCluster(cl)
produce two lists
:
$`1`
$`1`[[1]]
[,1] [,2]
[1,] 1 2
[2,] 2 4
[3,] 3 6
[4,] 4 8
$`2`
$`2`[[1]]
[,1] [,2]
[1,] 1 2
[2,] 2 4
[3,] 3 6
[4,] 4 8
How I combine this into a single data frame? Thank you!
Upvotes: 1
Views: 34
Reputation: 181
Either of these should work assuming you want to bind by row, if not use cbind or bind_cols. Unforutnaly your example isn't easily reproducible though.
df <- do.call("rbind", yourdata)
or:
library(dplyr)
df <- bind_rows(yourdata)
EDIT
I'm not sure if this is two seperate lists or a list of two data frames, if its two lists you could combine them as below and then use the above
lists <- do.call(c, list(list1, list2))
Upvotes: 1