简体   繁体   English

在 R 中,如何在不替换的情况下获取大小为 n 的样本,其中向量采样的长度为 <= n

[英]In R how do you take a sample of size n without replacement where length of vector sampling from is <= n

When I run the following I get an error:当我运行以下命令时,出现错误:

sample(c(1,4),5,replace=FALSE)

This is the error:这是错误:

  Error in sample.int(length(x), size, replace, prob) : 
  cannot take a sample larger than the population when 'replace = FALSE'

Is there a way to sample without replacement where it just automatically stops sampling once there is nothing left to sample?有没有一种无需更换的采样方法,一旦没有任何可采样的东西,它就会自动停止采样? The result in this case I would like to be 1,4 or 4,1.在这种情况下,我希望得到 1,4 或 4,1。

You can do it with an if else statement.您可以使用if else语句来做到这一点。

size_n <- 5
vec <- c(1, 4)

if (length(vec) < size_n) {
  sample(vec, length(vec), replace = F)
} else {
    sample(vec, size_n, replace = F)
  }

If we generalize the question in a way to "take sample size up to n" without replacement, we can do:如果我们将问题概括为“将样本大小增加到 n”而不进行替换,我们可以这样做:

population <- c(1, 4)
samplesize_max <- 5

sample(population, min(length(population), samplesize_max), replace = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R(和dplyr?)-按组从一个数据帧采样,最大采样量为n - R (and dplyr?) - Sampling from a dataframe by group, up to a maximum sample size of n R如何使用矢量作为采样大小对data.frame列表进行采样 - R How to sample a list of data.frame, with vector as sampling size 在R中向量的长度上从0递增到n - increment from 0 to n over the length of a vector in R 使用权重进行抽样并用 sample_n() function - Using weights for sampling with replacement with the sample_n() function 长度为 N 的向量的 n 级联(n 除 N),无需循环(在 R 中) - n-Concatenation of a vector of length N (n divides N) without looping (in R) R:从长度为 n 的向量中抽取 2 个长度为 n 的随机非重叠样本(对于相同的索引) - R: take 2 random non-overlapping samples (for same indexes) of length n out of vector of length n as well 使用向量长度作为某种权重,从不同长度的多个向量中进行采样而无需替换 - Sampling without replacement from multiple vectors of different length using vector lengths as some sort of weight 如何取 2 列生成长度为 N 的序列并添加为 R 中的列? - How to take 2 columns to generate sequence of length N and add as columns in R? R如何部分匹配向量与另一个n长度向量 - R how to partial match vector with another n-length vectors 在R中创建长度为N的相同数字的向量 - Create a Vector of Length N of the same numbers in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM