【发布时间】:2011-08-21 03:59:19
【问题描述】:
我有点困惑,为什么 R 中的 sd 函数会返回一个矩阵输入数组(我想保持向后兼容性,它总是会)。这对我来说是非常奇怪的行为:
#3d input, same same
print(length(mean(array(rnorm(60),dim=c(3,4,5)))))
print(length(sd(array(rnorm(60),dim=c(3,4,5)))))
#1d input, same same
print(length(mean(array(rnorm(60),dim=c(60)))))
print(length(sd(array(rnorm(60),dim=c(60)))))
#2d input, different!
print(length(mean(array(rnorm(60),dim=c(12,5)))))
print(length(sd(array(rnorm(60),dim=c(12,5)))))
我明白了
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 5
当输入是二维数组时,sd 的行为与mean 的行为不同(显然仅在这种情况下!)考虑一下,这个失败的函数重新缩放 k 维数组的每一列标准差:
re.scale <- function(x) {
#rescale by the standard deviation of each column
scales <- apply(x,2,sd)
ret.val <- sweep(x,2,scales,"/")
}
#this works just fine
x <- array(rnorm(60),dim=c(12,5))
y <- re.scale(x)
#this throws a warning
x <- array(rnorm(60),dim=c(3,4,5))
y <- re.scale(x)
如果没有这种奇怪的行为,是否有其他功能可以替换 sd?如何正确地写re.scale?还是按列的 Z 分数函数?
【问题讨论】:
-
为什么投反对票?这是一个非常合理、清晰的问题。
-
问题应该可能反映了 R >= 3.0 中的行为变化(见下面@Yoshiyuki 的回答)。
标签: r