r - Create a column of random integers, where the min and max integer for each row come from adjacent columns -
i have 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 add 4th column df
generates random number each row, lower , upper limits random integers sampled min
, max
values of row, respectively.
i have inkling should use sample()
, when returns column of values drawn randomly referenced column:
df$random <- sample(df$max)
could use runif
?
assuming dataframe df
as
letter min max 1 1 4 2 b 2 5 3 c 3 6
i have feeling there should better base r solution this. however, can try apply
, select (sample
) random number between 2 columns.
df$third_column <- apply(df, 1, function(x) sample(x[2]:x[3], 1)) df # letter min max third_column #1 1 4 1 #2 b 2 5 4 #3 c 3 6 4
Comments
Post a Comment