Reputation: 698
I have the following data frame DF
:
Min Max
10 20
14 34
9 29
... ...
and want to add a new column that samples a number between Min and Max of each row with uniform distribution. I've tried the below but give me the same number for all rows, meaning it's not sampling row by row as desired:
DF$random <- runif(1,min=DF$Min,max=DF$Max)
How may I achieve this?
Upvotes: 0
Views: 814
Reputation: 101916
Here is a base R solution
runif()
(thanks to comments by @David Arenburg)df$val <- with(df,runif(nrow(df),Min,Max))
Vectorize()
f <- Vectorize(function(x,y) runif(1,min=x,max=y),vectorize.args = c("x","y"))
df$val <- with(df,f(Min,Max))
such that
> df
Min Max val
1 10 20 14.51209
2 14 34 29.85087
3 9 29 22.97049
DATA
df <- structure(list(Min = c(10L, 14L, 9L), Max = c(20L, 34L, 29L)), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 1
Reputation: 174128
Try this:
library(dplyr)
DF <- data.frame(Min = c(10,14,9), Max= c(20,32,29))
DF %>% mutate(new_sample = mapply(function(x, y) runif(1, x, y), Min, Max))
# Min Max new_sample
# 1 1 10 2.581535
# 2 11 20 13.287205
# 3 21 30 23.546859
Upvotes: 1