Home > Back-end >  How to slice a matrix in R and keep the resulting column vector as an actual column vector indeed?
How to slice a matrix in R and keep the resulting column vector as an actual column vector indeed?

Time:01-27

The problem that I'm having can be illustrated using the following matrix:

b <- cbind(matrix(c(1, 0, 0), nrow = 3), 
           matrix(c(0, 0, 0), nrow = 3), 
           matrix(c(2, 0, 1), nrow = 3))

b
#      [,1] [,2] [,3]
# [1,]    1    0    2
# [2,]    0    0    0
# [3,]    0    0    1

Sometimes I need to slice matrices like the above, but when the slice keeps just one column or just one row the resulting slice then ceases to be a matrix. For instance, when I slice matrix b above and keep the last column and all rows as in the operation

b[seq(3), c(3)]

I get

# [1] 2 0 1

However, I would like to have the following result:

#      [,1]
# [1,]    2
# [2,]    0
# [3,]    1

What is a simple way to obtain the above result? Is there a slicing method that returns the result as above?

CodePudding user response:

b[seq(3), c(3), drop = FALSE]

Which can be simplified in this case to:

b[,3,drop = FALSE]
  • Related