我正在寻找一种聪明的方法来强制矩阵的维度(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]
显然最后一行没有给出理想的结果。如果不使用条件,是否有一种聪明的方法可以做到这一点?
答案 0 :(得分:1)
以您的解决方案为基础的一种方式:
#start rows and columns from 1
#also subtract remainder from total rows and columns
x[1:(nrow(x) - nrow(x) %% 2), 1:(ncol(x) - ncol(x) %% 2)]
输出:
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
答案 1 :(得分:1)
将nrow
和ncol
除以2
,取floor
,然后再乘以2
x.even = x[1:(2*floor(nrow(x)/2)),1:(2*floor(ncol(x)/2))]