How does the probability argument work in the sample() function in R

Viewed 132

I am trying to understand how the weighing works (probability argument) in the sample() function in R.

# seed
set.seed(123)

# some numbers
x = c(1:100)

# some probabilties
p = seq(from = 0, to = 1, length.out = 100)

# sample size
n = 10000

# sample 10000 times from x with probability p
x1 <- sample(x, size = n, replace = TRUE, prob = p)

# plot
hist(x1)
plot(density(x1))

Now is this approximately what the probability argument does?

# adding weights manually
weight = rep(x, n * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE) 

# plot
hist(x2)
plot(density(x2))

The plots look very similar so it seems that might be the case. enter image description here

EDIT

I think I made a mistake when I added the weights manually, i.e. I used n*p but I think I should have used x*p. Then the results do change a bit:

# adding weights manually
weight = rep(x, x * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE) 

enter image description here

1 Answers

The results you are getting are expected because by defining p as a sequence of evenly spaced numbers, the greater the value of x the greater its probability of being sampled. This is a weighted sampling procedure, like you say.

See the following two cases.

In the first case the probability of sampling element 2 is 4 times greater, and the results show approximately this.

set.seed(2022)

# sample size
n <- 10000

v <- 1:2
x <- sample(v, n, replace = TRUE, prob = c(1, 4)/5)
proportions(table(x))
#> x
#>      1      2 
#> 0.1976 0.8024
barplot(table(x))

In the case below, the probability of sampling a 10 is over 600 times greater than the probability of sampling any other number in the vector 1:100.

s <- 1:100
p <- rep(1, 100)
p[10] <- 400
p <- p/sum(p)
y <- sample(s, n, replace = TRUE, prob = p)
proportions(table(y))
hist(y)

Created on 2022-02-13 by the reprex package (v2.0.1)

Related