计算data.table中几列的z分数的平均值

时间:2017-03-17 14:10:52

标签: r data.table

在R中,我有一个数据表和一个带有数据表列名称子集的字符向量。我需要计算具有指定名称的每列的z分数(即与平均值的标准差的数量),并将z分数的平均值放在新列中。我发现了一个带有显式for循环的解决方案(在下面发布),但这必须是一个足够普遍的任务,可以使一些库函数更优雅地完成工作。还有更好的方法吗?

这是我的解决方案:

#! /usr/bin/env RSCRIPT

library(data.table)

# Sample data table.
dt <- data.table(a=1:3, b=c(5, 6, 3), c=2:4)

# List of column names.
cols <- c('a', 'b')

# Convert columns to z-scores, and add each to a new list of vectors.
zscores <- list()
for (colIx in 1:length(cols)) {
  zscores[[colIx]] <- scale(dt[,get(cols[colIx])], center=TRUE, scale=TRUE)
}

# Average corresponding entries of each vector of z-scores.
avg <- numeric(nrow(dt))
for (rowIx in 1:nrow(dt)) {
  avg[rowIx] <- mean(sapply(1:length(cols),
                            function(colIx) {zscores[[colIx]][rowIx]}))
}

# Add new vector to the table, and print out the new table.
dt[,d:=avg]
print(dt)

这给出了你所期望的。

   a b c           d
1: 1 5 2 -0.39089105
2: 2 6 3  0.43643578
3: 3 3 4 -0.04554473

1 个答案:

答案 0 :(得分:2)

scale可以应用于矩阵(类似)对象,您可以通过

获得所需的输出
> set(dt, NULL, 'd', rowMeans(scale(dt[, cols, with = F])))
> dt
   a b c           d
1: 1 5 2 -0.39089105
2: 2 6 3  0.43643578
3: 3 3 4 -0.04554473
相关问题