I am trying to make a data frame with 3 columns (and 100 rows) containing random numbers such that the random numbers in each row add to 72.
I am using this code to generate the random numbers:
random_numbers <- diff(c(0, sort(sample(72, 2)), 72))
Although, I can't "fit" these random numbers into a data frame because of the format. For example:
i <- 1:100
d <- data.frame(i)
d$rand <- diff(c(0, sort(sample(72, 2)), 72))
Error in `$<-.data.frame`(`*tmp*`, rand, value = c(37, 21, 14)) :
replacement has 3 rows, data has 100
I had another idea in which at least I can create all 100 random numbers:
results <- list()
for (i in 1:100) {
r_i <- diff(c(0, sort(sample(72, 2)), 72))
results[[i]] <- r_i
}
results[1]
# [[1]]
# [1] 3 19 50
results[2]
# [[1]]
# [1] 16 11 45
But I am not sure how I can I can create a data frame with 3 columns and 100 rows from this data.
I know how to do this in the "classical" sense:
i <- 1:100
r_1 <- rnorm(5, 5, 100)
r_2 <- rnorm(5, 5, 100)
r_3 <- rnorm(5, 5, 100)
d <- data.frame(i, r_1, r_2, r_3)
d = data.frame(i, r_1, r_2, r_3)
But of course, in the above data frame, these 3 numbers will most certainly not add to 72.
Is it possible to take the 100 random numbers results
that I generated above and then place them into a data frame?
CodePudding user response:
We may use replicate
with n
specified as the number of rows of 'd' and assign new columns from the matrix
output
d[paste0("r_", 1:3)] <- t(replicate(nrow(d),
diff(c(0, sort(sample(72, 2)), 72))))
-testing for equality
> all(rowSums(d[-1]) == 72)
[1] TRUE