Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use runif to calculate a column in data.table

Tags:

r

data.table

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?

like image 751
Kerry Avatar asked Jul 17 '15 03:07

Kerry


1 Answers

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.

like image 153
Ben Bolker Avatar answered Sep 22 '22 02:09

Ben Bolker