gpt4 book ai didi

r - data.table:使用 lapply 和 .SD 创建多列

转载 作者:行者123 更新时间:2023-12-04 01:47:28 25 4
gpt4 key购买 nike

<分区>

我正在尝试对 data.table 的多个列应用 scale() 函数来定义新列。我收到以下错误:

dt = data.table( id = rep( 1:10, each = 10 ), 
A = rnorm( 100, 1, 2 ),
B = runif( 100, 0, 1 ),
C = rnorm( 100, 10, 20 ) )


cols_to_use = c( "A", "B", "C" )
cols_to_define = paste0( cols_to_use, "_std" )

# working
dt[ , ( cols_to_define ) := lapply( .SD, scale ), .SDcols = cols_to_use ]

# not working
dt[ , ( cols_to_define ) := lapply( .SD, scale ), by = id, .SDcols = cols_to_use ]
## Error in `[.data.table`(dt, , `:=`((cols_to_define), lapply(.SD, scale)), :
## All items in j=list(...) should be atomic vectors or lists.
## If you are trying something like j=list(.SD,newcol=mean(colA)) then
## use := by group instead (much quicker), or cbind or merge afterwards.

知道为什么在删除 by 操作时有效吗?

25 4 0