Fastest way to add an element to a vector if it doesn't already exist in R
r, unique, vector
Solution
The `%chin%` operator from `data.table` is specially written to be fast for character vectors. Here is an example:
# Your data, and we would like to add elements from add
# that are not already in vect
vect <- c("a","b","c")
add <- c( "a" , "d" , "e" , "b" )
# Load package
require( data.table )
# %chin% operator is smae as %in% but fast and optimised for character sequences
c( vect , add[ ! add %chin% vect ] )
[1] "a" "b" "c" "d" "e"
Problem
I am looking for the fastest way in R to add an element (of type character) to a vector if it doesn't already exist. Right now I have simply ``` vect=c("a","b","c") vect=unique(c(vect,"b")) vect=unique(c(vect,"d")) ``` etc but I presume there must be better ways of doing this. Any thoughts? (my vector has about 2 million strings (web URLs) ) cheers, Tom