'In R, is there a way to generate a list of random numbers per row of a dataframe?
I want to use monte-carlo simulation to investigate the properties of certain kinds of dice systems which involve rolling a set of dice, and then picking the highest, possibly after having dropped the n highest dice.
To this end I've created a dataframe:
test <- data.frame(
dice_to_roll = sample.int(4, 100, TRUE),
highest_n_to_drop = sample(seq(0, 2), 100, TRUE)
)
Then for each row, I want to 'roll' a number of dice equal to dice_to_roll, and store them so that I can take max() or use nth() to drop a certain number, or perform other manipulations.
I know that
mutate(roll = max(sample.int(6, dice_to_roll, TRUE)))
doesn't work - it generates a single vector of length dice_to_roll, rather than a list for each row.
Is there an obvious way to do this that I'm missing?
Solution 1:[1]
Just found an answer for myself. Use rowwise:
test <- test %>%
rowwise() %>%
mutate(
results = max(sample.int(10, dice_to_roll, TRUE)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nllwrdobrn1 |
