Home > Back-end >  Creating data.frame of multiple random samples from a vector in R?
Creating data.frame of multiple random samples from a vector in R?

Time:11-13

I have the vector X and I would like to generate a data.frame of 6 integer samples of size 4. In other words, I would like to have a data.frame of 6 * 4 dimension. I tried the following the following but its throwing out lenght argument error.

set.seed(123)

X <- c(4,10,15,100,50,31,311,225,85,91)

S <- replicate(X, sample.int(n = 6, size = 4))

CodePudding user response:

We may need

replicate(4, sample(X, size = 6))

Or

replicate(6, sample(X, size = 4))

CodePudding user response:

Another base R solution.

set.seed(123)

X <- c(4,10,15,100,50,31,311,225,85,91)

dat <- as.data.frame(lapply(1:4, function(i) sample(X, size = 6))) %>%
  setNames(paste0("V", 1:4))

dat
#    V1  V2  V3  V4
# 1  15  50  50  85
# 2  91 100  15  15
# 3  10  31  85 225
# 4 225 225   4  10
# 5  31   4 100 311
# 6  85  10 311   4
  • Related