- 我很难表述问题的标题,因此如果有人可以提出更准确的标题,我将不胜感激。
我有一个由约 100 个样本和约 200,000 个特定位置的读数组成的矩阵。位置是字符串标识符,样本读数是数字。示例数据:
library(data.table)
str_col = c("str1", "str2", "str3")
s1 = c(54.4, 19.0, 89.0)
s2 = c(46.6, 39.5, 85.2)
s3 = c(12.3, 0.2, 55.8)
dt = data.table(str_col, s1, s2, s3)
dt
str_col s1 s2 s3
1: str1 54.4 46.6 12.3
2: str2 19.0 39.5 0.2
3: str3 89.0 85.2 55.8
我想计算样本列 (s1 - s3) 每个位置(行)读数的标准偏差,同时省略位置标识符 str_col
。
我的尝试是:
dt[, -1, with=FALSE][, stdv := apply(.SD, 1, sd)]
dt
str_col s1 s2 s3
1: str1 54.4 46.6 12.3
2: str2 19.0 39.5 0.2
3: str3 89.0 85.2 55.8
但是,如您所见,这只是返回原始 data.table。
我可以按如下步骤进行我想要的操作:
dt_str_col = dt[,.(str_col)]
dt2 = dt[, -1, with=FALSE][, stdv := apply(.SD, 1, sd)]
dt3 = data.table(dt_str_col, dt2)
dt3
str_col s1 s2 s3 stdv
1: str1 54.4 46.6 12.3 22.39695
2: str2 19.0 39.5 0.2 19.65613
3: str3 89.0 85.2 55.8 18.17067
但我想知道是否有一种方法可以通过在 data.table 中引用来做到这一点,类似于我的第一次尝试 dt[, -1, with=FALSE][, stdv := apply(.SD, 1、sd)]
?
最佳答案
我相信这会解决您的问题,不是吗?
dt[ , sdd := sd(.SD), by = str_col]
dt
#> str_col s1 s2 s3 sdd
#> 1: str1 54.4 46.6 12.3 22.4
#> 2: str2 19.0 39.5 0.2 19.7
#> 3: str3 89.0 85.2 55.8 18.2
如果每个 str_cols 有多于一行(即您确实想按行计算标准差),您可以这样做:
# create a column with row positions
dt[, rowpos := .I]
dt[ , sdd := sd(.SD[, -1, with=FALSE]), by = rowpos]
关于r - 子集 data.table 列用于计算新值,但保留所有旧列 + 新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37666370/