简体   繁体   中英

use runif to calculate a column in 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM