求教社区里的各位大神一个在向量切片(subsetting)中使用通道运算符(pipe)的实际操作问题。
有以下代码段落:
k=array(0,c(10,20))
for (i in 1:5)
{
for (j in 1:5)
{
k[2*i, c(2*j+1, 2*j+3, 2*j+4)]=rnorm(1)
}
}
这个代码段是没有问题的,其目的是对矩阵中某些有规律的位置上的元素进行改变(跟我实际需求相比做了简化,但不影响问题本质)。得到结果如下:
> print(k, digits=2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 0 0 0.00 0 0.00 0.00 0.00 0.00 0.000 0.00 0.00 0.000 0.00 0.00 0 0 0 0 0 0
[2,] 0 0 0.63 0 0.97 0.63 -0.68 0.97 0.059 -0.68 -1.13 0.059 -1.13 -1.13 0 0 0 0 0 0
[3,] 0 0 0.00 0 0.00 0.00 0.00 0.00 0.000 0.00 0.00 0.000 0.00 0.00 0 0 0 0 0 0
[4,] 0 0 -1.27 0 1.05 -1.27 0.29 1.05 1.230 0.29 0.47 1.230 0.47 0.47 0 0 0 0 0 0
[5,] 0 0 0.00 0 0.00 0.00 0.00 0.00 0.000 0.00 0.00 0.000 0.00 0.00 0 0 0 0 0 0
[6,] 0 0 -0.84 0 -0.82 -0.84 -0.24 -0.82 -0.713 -0.24 0.11 -0.713 0.11 0.11 0 0 0 0 0 0
[7,] 0 0 0.00 0 0.00 0.00 0.00 0.00 0.000 0.00 0.00 0.000 0.00 0.00 0 0 0 0 0 0
[8,] 0 0 -0.40 0 0.59 -0.40 -0.26 0.59 1.151 -0.26 -0.95 1.151 -0.95 -0.95 0 0 0 0 0 0
[9,] 0 0 0.00 0 0.00 0.00 0.00 0.00 0.000 0.00 0.00 0.000 0.00 0.00 0 0 0 0 0 0
[10,] 0 0 0.18 0 -0.45 0.18 -0.87 -0.45 1.820 -0.87 -2.01 1.820 -2.01 -2.01 0 0 0 0 0 0
我遇到的问题是当使用通道运算符进行简化的时候,矩阵并不会被修改:
library(magrittr)
k=array(0,c(10,20))
for (i in 1:5)
{
for (j in 1:5)
{
(2*j) %>% {k[2*i, c(.+1, .+3, .+4)]=rnorm(1)}
}
}
执行以上代码会得到以下结果:
> k
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
附系统环境信息:
> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Chinese (Simplified)_China.936 LC_CTYPE=Chinese (Simplified)_China.936 LC_MONETARY=Chinese (Simplified)_China.936
[4] LC_NUMERIC=C LC_TIME=Chinese (Simplified)_China.936
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] magrittr_1.5
loaded via a namespace (and not attached):
[1] tools_3.3.2
谢谢!