'Choose odd rows and columns from an original matrix [duplicate]

I'm trying to get the elements from odd rows and columns of a matrix. With the matrix being:

a = rbind(c(NA,2,-1,-2), c(0,1,3,0), c(0,NA,0,-1),c(3,1,5,NA))

I'm trying to get:

     [,1] [,2]
[1,]   NA   -1
[2,]    0    0

How could I create a new matrix C that only has those elements?



Solution 1:[1]

You can use the modulo operator %% to get odd rows and columns.

seq(nrow(a)) %% 2 == 1
# [1]  TRUE FALSE  TRUE FALSE

a[seq(nrow(a)) %% 2 == 1, seq(ncol(a)) %% 2 == 1]

#      [,1] [,2]
# [1,]   NA   -1
# [2,]    0    0

Solution 2:[2]

I think the easiest method would just be to recycle a logical vector for both rows and columns.

a[c(T,F), c(T,F)]
#>      [,1] [,2]
#> [1,]   NA   -1
#> [2,]    0    0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maël
Solution 2 AndS.