为什么R中的sd返回矩阵输入的向量,我该怎么办呢?

sha*_*hef 6 r

我有点困惑为什么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功能?

42-*_*42- 7

它在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)

  • 这是因为矩阵或数据框的列通常是感兴趣的变量的值.然后sd(矩阵)会告诉你变量的sds - 如果它是逐行的,那么你就会得到不相关的东西.那么,为什么然后,你说,并不意味着(矩阵)给列意味着?嗯,意思是(data.frame),所以这是一个线索,也许你应该使用数据帧.但对于矩阵,我认为它只是在开发早期阶段的一个糟糕的决定,这是一个特定领域的语言,当时没有多少人使用... (8认同)
  • FWIW,MatLab也这样做,显然"有人"认为这是个好主意.只做sd(as.vector(your_matrix)),一切都很好. (2认同)