简体   繁体   中英

Use sample() function to apply in a range of column

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!

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" 

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