[英]data.table, apply function to portion of a table
I want to apply function to portion of a table.我想将 function 应用于表格的一部分。
With data.frame, no problem:使用data.frame,没问题:
df <- data.frame(name = paste("a", 1:10, sep = "-"),
x = 1:10,
y = rep(1:5),
z = rep(1:2, each = 5))
df[2:5, -1] <- scale(df[2:5, -1], center = c(1,2,3), scale = c(4,5,6))
But data.table complains:但是 data.table 抱怨:
dt <- data.table(name = paste("a", 1:10, sep = "-"),
x = 1:10,
y = rep(1:5),
z = rep(1:2, each = 5))
dt[2:5, -1] <- scale(dt[2:5, -1], center = c(1,2,3), scale = c(4,5,6))
Error in
[<-.data.table
(*tmp*
, 2:5, -1, value = c(0.25, 0.5, 0.75, : Item 1 of column numbers in j is -1 which is outside range [1,ncol=4]. Use column names instead in j to add new columns.[<-.data.table
(*tmp*
, 2:5, -1, value = c(0.25, 0.5, 0.75, : j 中列号的第 1 项是 -1,超出范围 [1,ncol=4 ]. 在 j 中使用列名来添加新列。
What is the correct way in data.table? data.table 中的正确方法是什么? Thanks!
谢谢!
data.table
needs more work to apply scale
: data.table
需要更多的工作来应用scale
:
library(data.table)
cols <- names(dt)[-1]
dt[, (cols) := lapply(.SD, as.numeric), .SDcols = cols]
dt[2:5, (cols) := Map(scale, .SD, c(1,2,3), c(4,5,6)), .SDcols = cols]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.