Search code examples
rrandomuniform-distribution

R row-wise runif() between 2 columns


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?


Solution

  • Here is a base R solution

    • just runif() (thanks to comments by @David Arenburg)
    df$val <- with(df,runif(nrow(df),Min,Max))
    
    • using 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))