uncool uncool - 4 months ago 14
R Question

Remove vector element with %in% returns character(0)

Got a quick question. I'm trying to remove a vector element with the code below. But I get

character(0)
returned instead of the rest of the vector elements.

What have I done wrong?

> str(ticker.names)
chr [1:10] "AAK.ST" "ABB.ST" "ALFA.ST" "ALIV-SDB.ST" "AOI.ST" "ASSA-B.ST" "ATCO-A.ST" "ATCO-B.ST" "AXFO.ST" "AXIS.ST"
> ticker.names[! 'AAK.ST' %in% ticker.names]
character(0)

Answer

If we need to remove the elements in `ticker.names' that are not 'AAK.ST'.

ticker.names[!ticker.names %in% 'AAK.ST']

Or use setdiff

setdiff(ticker.names, 'AAK.ST')

Consider the approach OP is using,

'AAK.ST' %in% ticker.names
#[1] TRUE
ticker.names['AAK.ST' %in% ticker.names]
#[1] "AAK.ST"  "ABB.ST"  "ALFA.ST"

By negating,

!'AAK.ST' %in% ticker.names
#[1] FALSE

ticker.names[!'AAK.ST' %in% ticker.names]
#character(0)

In the former case, the TRUE is recycled to the length of the 'ticker.names', so all the elements of the vector are returned, while in the latter, the FALSE gets recycled and no elements are returned.

data

ticker.names <- c('AAK.ST', 'ABB.ST', 'ALFA.ST')