Search code examples
rarray-indexing

R - forcing a set of indexed rows to always be a matrix (or array)


I have a matrix that I need to filter by a condition.

yj = y[which(g[,j] == 1),]

A problem arises when "which(g[,j] == 1)" is a 1 (or none) component vector. The output, the aforementioned "yj", is then suddenly a vector. I need to be able to reference it by column. Even if it's a single row, it still needs to be reference-able by column.

How do I make this happen?


Solution

  • Use drop = FALSE while subsetting.

    yj = y[which(g[,j] == 1),, drop = FALSE]
    

    If which(g[,j] == 1) can be of length 0 better to check for it using if condition.

    inds <- which(g[,j] == 1)
    if(inds) yj = y[inds, ,drop = FALSE]