0

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?

Faydey
  • 725
  • 1
  • 5
  • 12

1 Answers1

2

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]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213