我有点困惑为什么sdR中的函数返回一个矩阵输入的数组(我想保持向后兼容性,它总是会).这对我来说是非常奇怪的行为:
#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)))))
Run Code Online (Sandbox Code Playgroud)
我明白了
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 5
Run Code Online (Sandbox Code Playgroud)
这与输入是2-d数组时的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)
Run Code Online (Sandbox Code Playgroud)
sd如果没有这种奇怪的行为,还有其他一些功能需要替换吗?如何re.scale正确写?或者Z-score-by-column功能?
它在sd的帮助页面中表现为文档.在最顶层宣布:
"如果x是矩阵或数据帧,则返回列的标准偏差向量."
请注意,它并未说明包含数组,因此仅包含具有两个维度的数组.如果你想停止这种行为,那么只需用c()创建一个向量:
sd( c(array(rnorm(60),dim=c(12,5))) )
# [1] 0.9505643
Run Code Online (Sandbox Code Playgroud)
我看到你添加了列z分数的请求.试试这个矩阵:
colMeans(x)/sd(x)
Run Code Online (Sandbox Code Playgroud)
对于数组而言(尽管"列"的定义可能需要澄清:
apply(x, 2:3, mean)/apply(x, 2:3, sd) # will generalize to higher dimensions
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1141 次 |
| 最近记录: |