uncool uncool - 6 months ago 40
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

returned instead of the rest of the vector elements.

What have I done wrong?

> str(ticker.names)
> ticker.names[! 'AAK.ST' %in% ticker.names]


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]

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.


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