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?
CodePudding user response:
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
CodePudding user response:
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