Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sampling from uniform distribution row wise in R

Consider the following data:

df <- data.frame(id=1:5,
                 x_min = c(0.1,0.2,0.3,0.4,0.5),
                 x_max = c(0.15,0.23,0.38,0.44,0.57))

I intend to draw a random sample from a uniform distribution for each row. Why I’m getting the same values for column y? Here is what I did:

set.seed(12)
df$y <- runif(1, min=df$x_min, max=df$x_max)

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> df
  id x_min x_max        y
1  1   0.1  0.15 0.103468
2  2   0.2  0.23 0.103468
3  3   0.3  0.38 0.103468
4  4   0.4  0.44 0.103468
5  5   0.5  0.57 0.103468

>Solution :

That is because runif(1, min=df$x_min, max=df$x_max) evaluates to a single number. Replace 1 with nrow(df).

df <- data.frame(id=1:5,
                 x_min = c(0.1,0.2,0.3,0.4,0.5),
                 x_max = c(0.15,0.23,0.38,0.44,0.57))

set.seed(12)
df$y <- runif(1, min=df$x_min, max=df$x_max)

df
#>   id x_min x_max        y
#> 1  1   0.1  0.15 0.103468
#> 2  2   0.2  0.23 0.103468
#> 3  3   0.3  0.38 0.103468
#> 4  4   0.4  0.44 0.103468
#> 5  5   0.5  0.57 0.103468

set.seed(12)
df$y <- runif(nrow(df), min=df$x_min, max=df$x_max)

df
#>   id x_min x_max         y
#> 1  1   0.1  0.15 0.1034680
#> 2  2   0.2  0.23 0.2245333
#> 3  3   0.3  0.38 0.3754097
#> 4  4   0.4  0.44 0.4107753
#> 5  5   0.5  0.57 0.5118544

Created on 2023-02-26 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading