bioinformatics2020
bioinformatics2020

Reputation: 89

Which With a Logical Vector Returning Integer(0)

A little perplexed by this. I have a logical vector as such:

logical_vec <- c(TRUE, FALSE)

I am interested in capturing the indices of this logical vector so that I can subset another R object. For example, if I am interested in the position of the TRUE element, I thought I would use this:

which(TRUE, logical_vec) 
[1] 1

But when trying to find which index is FALSE, I get an integer(0) error.

which(FALSE, logical_vec)
integer(0)

Does which only return conditions that satisfy as TRUE or am I doing something incorrect here?

Upvotes: 1

Views: 124

Answers (2)

akrun
akrun

Reputation: 887691

which takes a single argument for 'x' and by passing two arguments, it takes the first one as 'x' and second argument by default is arr.ind = FALSE. According to ?which

which(x, arr.ind = FALSE, useNames = TRUE)

where

x - a logical vector or array. NAs are allowed and omitted (treated as if FALSE).

which(FALSE)
integer(0)

We may need to concatenate (c) to create a single vector instead of two arguments

which(c(FALSE, logical_vec))
[1] 2

Also, there is no need to do == on a logical vector - which by default gets the postion index of logical vector and if we need to negate, use !

which(logical_vec)
[1] 1
which(!logical_vec)
[1] 2

Upvotes: 2

Ben
Ben

Reputation: 106

Maybe this is what you want? Note that you supply a second argument arr.ind, which is not what you want.

logical_vec <- c(TRUE, FALSE)
which(logical_vec == TRUE)
#> [1] 1
which(logical_vec == FALSE)
#> [1] 2

Created on 2021-09-06 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions