Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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)
like image 525
uncool Avatar asked Mar 14 '23 19:03

uncool


1 Answers

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')
like image 106
akrun Avatar answered Apr 05 '23 03:04

akrun