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:
> 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
That is because runif(1, min=df$x_min, max=df$x_max)
evaluates to a single number. Replace 1
with nrow(df)
to ensure the correct number of simulated uniform values.
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