简体   繁体   中英

R: how to write a function that samples given the probability

I wrote a function

p = c(0.4, 0.6)
myfun = function(p){
    sample(1:2, 1, replace = TRUE, prob = p)
}

And I want to repeat this 5 times.

sapply(1:5, myfun)

But this gives me an error

Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities

You could write your function with 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

You can use the sample function to sample 5 values.

p <- c(0.4, 0.6)
sample(1:2, 5, replace = TRUE, prob = p)
# [1] 2 2 2 2 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM