John Godlee John Godlee - 1 year ago 49
R Question

Create a column of random integers, where the min and max integer for each row come from adjacent columns

I have a data frame:

letter <- c("A", "B", "C")
min <- c(1, 2, 3)
max <- c(4, 5, 6)
df <- data.frame(letter, min, max)

I want to add a 4th column to
which generates a random number for each row, where the lower and upper limits from which the random integers are sampled from are the
values of that row, respectively.

I have an inkling that I should use
, but when I do it returns a column of values drawn randomly from the referenced column:

df$random <- sample(df$max)

Could I also use

Answer Source

Assuming your dataframe df as

   letter min max
1      A   1   4
2      B   2   5
3      C   3   6

I have a feeling there should be a better base R solution than this. However, for now we can try with apply and select (sample) any random number between the two columns.

df$third_column <- apply(df, 1, function(x) sample(x[2]:x[3], 1))

#  letter min max third_column
#1      A   1   4            1
#2      B   2   5            4
#3      C   3   6            4