如何在R矩阵中找到移动标准差?
要以与在数据框中相同的方式在矩阵中找到移动标准差,我们只需要使用矩阵对象名称代替数据框名称。因此,我们可以为此使用zoo包的rollapply功能。
例如,如果我们有一个名为M的矩阵,并且我们想要找到2个移动标准差,那么我们可以使用以下给定的命令-
rollapply(M,width=2,FUN=sd,fill=0,align="r")
示例1
以下代码段创建了一个矩阵-
M1<-matrix(rnorm(40),ncol=2) M1
创建以下矩阵-
[,1] [,2] [1,] 0.345787411 0.43349738 [2,] 0.430162396 0.27067794 [3,] 1.103564081 -1.04460809 [4,] -0.580082754 -0.25060257 [5,] 1.927945086 -0.89618197 [6,] -0.280682051 -1.80365388 [7,] -0.001555098 -0.39360239 [8,] 1.326034225 -1.07766271 [9,] -1.397108815 0.23207688 [10,] 1.011509167 0.34147468 [11,] 0.334467618 1.26899363 [12,] 0.108641768 0.11525723 [13,] -0.002091529 0.93016179 [14,] -0.714714754 1.31114310 [15,] -1.186013755 -0.63420972 [16,] -0.126330767 -0.07257558 [17,] -0.971670037 1.03083570 [18,] -1.216119558 -0.03943005 [19,] 1.016730169 1.06252932 [20,] -0.706784197 0.09479385
要加载zoo包并找到矩阵M1的2-moving标准差,请将以下代码添加到上述代码段中-
library(zoo) rollapply(M1,width=2,FUN=sd,fill=0,align="r")输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出-
[,1] [,2] [1,] 0.00000000 0.00000000 [2,] 0.05966212 0.11513073 [3,] 0.47616690 0.93004767 [4,] 1.19051809 0.56144668 [5,] 1.77344349 0.45649357 [6,] 1.56173523 0.64167954 [7,] 0.19737256 0.99705697 [8,] 0.93874741 0.48370369 [9,] 1.92555291 0.92612575 [10,] 1.70315011 0.07735593 [11,] 0.47874067 0.65585494 [12,] 0.15968299 0.81581483 [13,] 0.07830026 0.57622454 [14,] 0.50390071 0.26939447 [15,] 0.33325872 1.37557217 [16,] 0.74930903 0.39713531 [17,] 0.59774513 0.78022959 [18,] 0.17285191 0.75679217 [19,] 1.57886318 0.77920294 [20,] 1.21870870 0.68429231
示例2
以下代码段创建了一个矩阵-
M2<-matrix(rpois(60,10),ncol=3) M2
创建以下矩阵-
[,1][,2][,3] [1,] 11 9 6 [2,] 3 10 8 [3,] 12 10 5 [4,] 8 10 4 [5,] 14 7 10 [6,] 3 10 10 [7,] 10 10 9 [8,] 7 9 8 [9,] 11 11 14 [10,] 6 9 9 [11,] 14 13 14 [12,] 9 11 9 [13,] 12 11 6 [14,] 10 14 7 [15,] 8 14 13 [16,] 21 10 8 [17,] 15 7 10 [18,] 9 15 9 [19,] 10 8 8 [20,] 17 10 7
要找到矩阵M2的4移动标准差,请将以下代码添加到上述代码段中-
rollapply(M2,width=4,FUN=sd,fill=0,align="r")输出结果
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出-
[,1] [,2] [,3] [1,] 0.000000 0.0000000 0.0000000 [2,] 0.000000 0.0000000 0.0000000 [3,] 0.000000 0.0000000 0.0000000 [4,] 4.041452 0.5000000 1.7078251 [5,] 4.856267 1.5000000 2.7537853 [6,] 4.856267 1.5000000 3.2015621 [7,] 4.573474 1.5000000 2.8722813 [8,] 4.654747 1.4142136 0.9574271 [9,] 3.593976 0.8164966 2.6299556 [10,] 2.380476 0.9574271 2.7080128 [11,] 3.696846 1.9148542 3.2015621 [12,] 3.366502 1.6329932 2.8867513 [13,] 3.500000 1.6329932 3.3166248 [14,] 2.217356 1.5000000 3.5590261 [15,] 1.707825 1.7320508 3.0956959 [16,] 5.737305 2.0615528 3.1091264 [17,] 5.802298 3.4034296 2.6457513 [18,] 6.020797 3.6968455 2.1602469 [19,] 5.500000 3.5590261 0.9574271 [20,] 3.862210 3.5590261 1.2909944