Reputation: 97
I have a data.frame called "prob" with 3 columns of probabilities.
A B C
1 0.346 0.629 0.026
2 0.377 0.529 0.094
3 0.454 0.495 0.051
4 0.338 0.604 0.058
5 0.616 0.331 0.054
I want to sample one item from (A,B,C) in each row. So I apply the following function:
sapply(prob[,2:5],
function(p) sample(x = c(0:2), size = 1, prob = p))
R returns an error:
Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities
How can I solve this? Thanks!
Upvotes: 1
Views: 2003
Reputation: 1530
df <- structure(list(A = c(0.346, 0.377, 0.454, 0.338, 0.616), B = c(0.629, 0.529, 0.495, 0.604, 0.331), C = c(0.026, 0.094, 0.051, 0.058, 0.054)), .Names = c("A", "B", "C"), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))
apply(df, 1, function(x) sample(names(df), 1, prob = x))
output
1 2 3 4 5
"B" "C" "A" "A" "B"
Upvotes: 2