Using replication for user define fuction containing mapply and list of results
I can use the following MyFun
(user-defined) function to simulate observations. But failed to figure out how to iterate this function with a function replicate
when the function returns a list of output. Any help would be much appreciated. thank
MyFun <- function(nSim, Size, Prob) {
M1 <- t(mapply(rbinom, prob = Prob, n = nSim, size = Size))
dimnames(M1) <- list(Prob, paste0("V", 1:nSim))
MeanM1 <- M1/Size
Results1 <- list(M1, MeanM1)
return(Results1)
}
MyFun(nSim=5, Size=4, Prob=c(0.2, 0.4))
[[1]]
V1 V2 V3 V4 V5
0.2 2 2 1 2 1
0.4 2 3 0 3 1
[[2]]
V1 V2 V3 V4 V5
0.2 0.5 0.50 0.25 0.50 0.25
0.4 0.5 0.75 0.00 0.75 0.25
But doesn't give the desired results with the function replicate
.
replicate(
n=2
, MyFun(nSim=5, Size=2, Prob=c(0.2, 0.4))
, simplify = "array"
)
[,1] [,2]
[1,] Integer,10 Integer,10
[2,] Numeric,10 Numeric,10
source to share
Try adding a simplifying argument to your function and pass it in mapply()
.
MyFun <- function(nSim, Size, Prob, simplify = "array") {
M1 <- t(
mapply(rbinom, prob = Prob, n = nSim, size = Size, SIMPLIFY = simplify)
)
dimnames(M1) <- list(Prob, paste0("V", 1:nSim))
MeanM1 <- M1/Size
Results1 <- list(M1, MeanM1)
return(Results1)
}
Then call it like this using simplify = FALSE
in replicate()
. This will create a list of length 2 with a list of two arrays per element.
replicate(2, MyFun(nSim=5, Size=2, Prob=c(0.2, 0.4)), simplify = FALSE)
[[1]]
[[1]][[1]]
V1 V2 V3 V4 V5
0.2 1 0 2 0 0
0.4 2 0 1 1 0
[[1]][[2]]
V1 V2 V3 V4 V5
0.2 0.5 0 1.0 0.0 0
0.4 1.0 0 0.5 0.5 0
[[2]]
[[2]][[1]]
V1 V2 V3 V4 V5
0.2 0 0 0 0 1
0.4 2 1 1 1 0
[[2]][[2]]
V1 V2 V3 V4 V5
0.2 0 0.0 0.0 0.0 0.5
0.4 1 0.5 0.5 0.5 0.0
source to share
Your function actually works, it only has "weird" output. Try to save the result to an object named aa
.
aa <- replicate(
+ n=2
+ , MyFun(nSim=5, Size=2, Prob=c(0.2, 0.4))
+ , simplify = T
+ )
aa
[,1] [,2]
[1,] Integer,10 Integer,10
[2,] Numeric,10 Numeric,10
but each element of this 2 x 2 matrix is ββitself a matrix. Try the following:
class(aa)
[1] "matrix"
sapply(aa, class)
[1] "matrix" "matrix" "matrix" "matrix"
In fact, if you retrieve the first "cell" of the previous matrix, you will see that it is the matrix that contains the output MyFun
:
aa[1,1]
[[1]]
V1 V2 V3 V4 V5
0.2 0 1 0 0 1
0.4 1 2 0 2 0
source to share