r - using foreach and %dopar% to output the desired results -
so in simplistic world, lets take data:
set.seed(123) require(doparallel) cl<-makecluster(2) registerdoparallel(cl) m <- 10 result = foreach(i=1:m,.combine=cbind) %dopar% { rows <- (1:10) <- rnorm(10, 5, 1) <- round(a, 0) b <- rnorm(10, 6, 1) b <- round(b, 0) df <- data.frame(rows,a,b) output_1 <- length(df$a[df$a == df$b]) # save number of accounts == b output_2 <- length(df$a[df$a != df$b]) # save number of accounts , b not equal result <- rbind(output_1,output_2) }
using can check our output
result[1,] result[2,]
but want include rows (a string of row identities, not count) correspond a!=b in output of result
the problem not single value , varies per alteration. how can 1 achieve this?
update
if add
output_3 <- setdiff(df$rows, df$rows[df$a == df$b])
and adjust
result <- rbind(output_1,output_2, output_3)
we run more simulations required
here apparently desire:
set.seed(123) require(doparallel) cl<-makecluster(2) registerdoparallel(cl) m <- 10 result = foreach(i=seq_len(m)) %dopar% { rows <- (1:10) <- rnorm(10, 5, 1) <- round(a, 0) b <- rnorm(10, 6, 1) b <- round(b, 0) df <- data.frame(rows,a,b) output_1 <- length(df$a[df$a == df$b]) # save number of accounts == b output_2 <- length(df$a[df$a != df$b]) # save number of accounts , b not equal list(rbind(output_1, output_2), which(df$a != df$b)) } stopcluster(cl)
this returns list of lists. note need use package dorng if want pass random seed workers.
this vectorized approach use:
set.seed(42) <- matrix(round(rnorm(m * 10, 5, 1), 0), ncol = m) b <- matrix(round(rnorm(m * 10, 6, 1), 0), ncol = m) which(a != b, arr.ind = true) colsums(a != b) colsums(a == b)
Comments
Post a Comment