【发布时间】:2017-07-10 06:10:28
【问题描述】:
我正在寻找一种巧妙的方法来强制矩阵的维度(nrow 和 ncol)均匀不使用 if 语句。 force 我的意思是减去第一个适当的列和/或行,以便两个维度都是偶数。
我希望这样的事情会起作用:
## build a matrix with odd number of columns and even number of rows
x=matrix(1:12,nrow=4,ncol=3)
## we can check which (if any) dimensions are odd with
dim(x) %% 2 ## 0,1
## I would like get a matrix that looks like
[,1] [,2]
[1,] 5 9
[2,] 6 10
[3,] 7 11
[4,] 8 12
## By using something similar to
x.even = x[-nrow(x)%%2,-ncol(x)%%2]
显然最后一行没有给出想要的结果。有没有不使用条件的聪明方法?
【问题讨论】:
-
x.even = x[1:(2*floor(nrow(x)/2)),1:(2*floor(ncol(x)/2))] -
我喜欢它!干杯!