R: Sample a vector with replacement multiple times

前端 未结 3 1182
时光取名叫无心
时光取名叫无心 2020-12-31 08:55

I\'d like to sample a vector x of length 7 with replacement and sample that vector 10 separate times. I\'ve tried the something like the following but can\'t get the result

3条回答
  •  盖世英雄少女心
    2020-12-31 09:37

    Since you seem to want to sample with replacement, you can just get the 7*10 samples at once (which is more efficient for large sizes):

    x <- runif(7)
    n <- 10
    xn <- length(x)
    matrix(x[sample.int(xn, xn*n, replace=TRUE)], nrow=xn)
    
    # Or slightly shorter:
    matrix(sample(x, length(x)*n, replace=TRUE), ncol=n)
    

    The second version uses sample directly, but there are some issues with that: if x is a numeric of length 1, bad things happen. sample.int is safer.

    x <- c(pi, -pi)
    sample(x, 5, replace=T) # OK
    x <- pi
    sample(x, 5, replace=T) # OOPS, interpreted as 1:3 instead of pi...
    

提交回复
热议问题