dt = data.table( v = rnorm(40) , g = rep(c("a","b"),20) )
> head(dt)
v g 1: 0.5331207 a 2: -1.1228596 b 3: -0.5366661 a 4: -0.3221877 b 5: 0.1945076 a 6: -0.6483930 b
我想对每个组进行内核密度估计,并将结果存储在新的data.table
中。因此,在data.table
的每个组上执行的函数将自己返回matrix
或data.table
失败的尝试:
dt[, .( { tmp = density(x=v) ; list(x=tmp$x,y=tmp$x) } ) , by = .(g) ]
dt[, .( { tmp = density(x=v) ; data.table(x=tmp$x,y=tmp$x) } ) , by = .(g) ]
所需结果:
> x y g > -0.5 0.003 a > -0.45 0.0413 a ... > 0.8 0.0013 a ... > -0.5 0.0026 b > -0.45 0.0034 b ...