我有大量的数据点,每个数据点都有不同的相关概率为0或1.在R中是否有办法创建从这些概率中采样的0和1的向量?以下代码显示了如何执行我想要的操作,但它处于循环中。
n <- 10
x <- letters[1:n] # my data
p <- runif(n) # my probabilities of the result being 1
result <- numeric()
for(ii in 1:n){
result[ii] <- sample(x = c(0,1), 1, prob = c(1-p[ii], p[ii]))
}
print(cbind(x, p, result))
结果如下:
x p result
[1,] "a" "0.0407166101504117" "0"
[2,] "b" "0.632280522491783" "1"
[3,] "c" "0.754841333255172" "0"
[4,] "d" "0.0509465073700994" "0"
[5,] "e" "0.629663853673264" "0"
[6,] "f" "0.357108945958316" "0"
[7,] "g" "0.808141406625509" "1"
[8,] "h" "0.671664241468534" "1"
[9,] "i" "0.0218871515244246" "1"
[10,] "j" "0.689538966864347" "1"
答案 0 :(得分:3)
我不确定我是否理解正确,因为我对这些字母感到困惑......这个怎么样?
set.seed(1) # reproducibility
n <- 10
p <- runif(n) # probabilities
result <- rbinom(n,1,p)
cbind(p,result)
p result
[1,] 0.26550866 0
[2,] 0.37212390 0
[3,] 0.57285336 0
[4,] 0.90820779 1
[5,] 0.20168193 0
[6,] 0.89838968 1
[7,] 0.94467527 1
[8,] 0.66079779 0
[9,] 0.62911404 1
[10,] 0.06178627 0