John Godlee John Godlee - 22 days ago 9
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
df
which generates a random number for each row, where the lower and upper limits from which the random integers are sampled from are the
min
and
max
values of that row, respectively.

I have an inkling that I should use
sample()
, 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
runif
?

Answer

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))
df

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