简体   繁体   中英

R: trouble with specifying probability for sample function

> sample(c(2), 10, replace = TRUE, prob = 1)
Error in sample.int(x, size, replace, prob) : 
  incorrect number of probabilities
> sample(c(1), 10, replace = TRUE, prob = 1)
 [1] 1 1 1 1 1 1 1 1 1 1

In the first example, I would like to sample the vector 2 ten times, with replacement, each with probability = 1. I would expect the output to be 2 2 2 2 2 2 2 2 2 2

However, it seems to work with a vector of 1 ?

Try removing the prob = 1 and what do you get?

> set.seed(123)
> sample(c(2), 10, replace = TRUE)
# [1] 1 2 1 2 2 1 2 2 2 1

help(sample)

Usage

sample(x, size, replace = FALSE, prob = NULL)

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x). See the examples.

So, it's sampling from 1:2 not 2 .

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