icz
icz

Reputation: 547

multicore::sapply?

Is there anything like sapply in the multicore library? Or do I have to unlist(mclapply(..)) in order to achieve this?

If it does not exist: what would the reasoning be?

Thanks in advance and sorry if this is a stupid question!

Upvotes: 4

Views: 5284

Answers (3)

francois artin
francois artin

Reputation: 36

just like IRTFM mentionned, looking at source code of sapply is the answer. But since I was still a bit confused after reading his answer, maybe it's me, so if you were too then hopefully following precision will make it clearer : code of sapply :

sapply<-function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) 
{
  FUN <- match.fun(FUN)
  answer <- lapply(X = X, FUN = FUN, ...)
  if (USE.NAMES && is.character(X) && is.null(names(answer))) 
    names(answer) <- X
  if (!isFALSE(simplify) && length(answer)) 
    simplify2array(answer, higher = (simplify == "array"))
  else answer
}

so a homemade implementation of mcsapply would be :

mcsapply<-function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE, mc.preschedule = TRUE,
 mc.set.seed = TRUE, mc.silent = FALSE, mc.cores = getOption("mc.cores", 2L), 
  mc.cleanup = TRUE, mc.allow.recursive = TRUE, affinity.list = NULL )
{
  answer <- mclapply(X = X, FUN = FUN, ...,mc.preschedule = mc.preschedule, 
mc.set.seed = mc.set.seed, mc.silent = mc.silent, mc.cores = mc.cores, 
  mc.cleanup = mc.cleanup, mc.allow.recursive = mc.allow.recursive, affinity.list = affinity.list)
  if (USE.NAMES && is.character(X) && is.null(names(answer))) 
    names(answer) <- X
  if (!isFALSE(simplify) && length(answer)) 
    simplify2array(answer, higher = (simplify == "array"))
  else answer
}

I am using similar implementation and it works just fine.

Upvotes: 1

nograpes
nograpes

Reputation: 18323

In the library parallel, you have mcmapply which, like mapply in base, takes a SIMPLIFY argument. It is TRUE by default. Here is an example use:

library(parallel)
mcmapply(sqrt,split(1:8,1:8))
#        1        2        3        4        5        6        7        8
# 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427

Compare this to the use of mclapply.

mclapply(split(1:8,1:8),sqrt)
# $`1`
# [1] 1
# 
# $`2`
# [1] 1.414214
# ...

Upvotes: 5

IRTFM
IRTFM

Reputation: 263391

If you look at the code of sapply (and its helper function simplify2array) you will see that unlist(obj) is exactly what will be done in the case where obj is a list of items all of length==1. sapply is a lot more complex than just unlisting lists, however. What is still very unclear is what problem you are trying to solve.

Upvotes: 3

Related Questions