sapply - R: how to write a function that samples given the probability -
sapply - R: how to write a function that samples given the probability -
i wrote function
p = c(0.4, 0.6) myfun = function(p){ sample(1:2, 1, replace = true, prob = p) }
and want repeat 5 times.
sapply(1:5, myfun)
but gives me error
error in sample.int(length(x), size, replace, prob) : wrong number of probabilities
you write function replicate
.
myfun <- function(x, p, n, replace = true) { m <- replicate(n, sample(x, replace = replace, prob = p)) if(n == 1) c(m) else m } myfun(2, c(0.4, 0.6), 5) # [,1] [,2] [,3] [,4] [,5] # [1,] 1 1 2 2 2 # [2,] 2 2 2 1 2 myfun(2, c(0.4, 0.6), 1) # [1] 2 1
r sapply
Comments
Post a Comment