Diorne
Diorne

Reputation: 197

How to select elements of a vector properly?

Why does filtering elements of a vector with '[]' results in NA, while 'which' function does not return any NA?

Here is an example:

setor <- c('residencial','residencial',NA,'comercial')
setor[setor == 'residencial']
#"residencial" "residencial" NA`

setor[which(setor=='residencial')]
#[1] "residencial" "residencial"

Your help would be much appreciated!

Upvotes: 1

Views: 48

Answers (2)

akrun
akrun

Reputation: 887961

We could use %in%, which returns FALSE where there are NA elements

setor %in% 'residencial'
#[1]  TRUE  TRUE FALSE FALSE

It also works when we need to subset more than one element, i.e.

setor %in% c('residencial', 'comercial')
#[1]  TRUE  TRUE FALSE  TRUE

and this can be directly used to subset

setor[setor %in% 'residencial']
#[1] "residencial" "residencial"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

Because when you use == for comparison it returns NA for NA values.

setor == 'residencial'
#[1]  TRUE  TRUE    NA FALSE

and subsetting with NA returns NA

setor[setor=='residencial']
#[1] "residencial" "residencial" NA  

However, when we use which it doesn't count NA's and returns index of only TRUE values.

which(setor=='residencial')
#[1] 1 2

setor[which(setor=='residencial')]
#[1] "residencial" "residencial"

Upvotes: 4

Related Questions