I would like to generate a random number using runif for each row in a data table. Unfortunately, I end up with the same number in every row.
require(data.table)
dx <- data.table( min=1:10, max=seq(10,100,10))
dx[, sum:=min+max]
dx[, runif:=runif(n=1,min,max)]
> dx
min max sum runif
1: 1 10 11 5.086488
2: 2 20 22 5.086488
3: 3 30 33 5.086488
4: 4 40 44 5.086488
5: 5 50 55 5.086488
6: 6 60 66 5.086488
7: 7 70 77 5.086488
8: 8 80 88 5.086488
9: 9 90 99 5.086488
10: 10 100 110 5.086488
Why does runif behave this way but addition works just fine? Can someone suggest how to use the min and max on each row to generate a uniformly distributed random number for that row?
I think just
dx[, runif := runif(.N, min, max)]
should do it. By setting n=1
you were requesting that a single value be generated, which was then recycled to the appropriate length. min
and max
are still handled in the appropriate, vectorized way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With