[R] Drawing a sample based on certain condition

Ebert,Timothy Aaron
2025-04-14T12:30:35Z

1) extract relevant observations to a new data frame. Either of these two
commands works.
filter(df, age > 24)
df[df$age > 24, ]
2) sample the new data frame
df[sample(nrow(df), 10, replace = TRUE), ]
change TRUE to FALSE if you do not want replacement.


Tim
-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Brian Smith
Sent: Monday, April 14, 2025 7:27 AM
To: r-help at r-project.org
Subject: [R] Drawing a sample based on certain condition

[External Email]

Hi,

For my analytical work, I need to draw a sample of certain sample size from a
denied population, where population members are marked by non-negative integers,
such that sum of sample members if fixed. For example,

Population = 0:100
Sample_size = 10
Sample_Sum = 20

Under this setup if my sample members are X1, X2, ..., X10 then I should have
X1+X2+...+X10 = 20

Sample drawing scheme may be with/without replacement

Is there any R function to achieve this? One possibility is to employ naive
trial-error approach, but this doesnt seem to be practical as it would take long
time to get the final sample with desired properties.

Any pointer would be greatly appreciated.

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.r-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.