Reputation: 457
For example, I have 2 chairs and one table in set1 and 1 chair in set2.
I want to subtract set2 from set1 and want the result as c("chair", "table")
set1 <- c("chair", "chair", "table")
set2 <- c("chair")
setdiff(set1, set2)
gives "table"
Upvotes: 3
Views: 1466
Reputation: 13701
The package vecsets
will perform set operations on vectors while retaining duplicates:
vecsets::vsetdiff( c("chair", "chair", "table"), c("chair") )
# [1] "chair" "table"
Upvotes: 0
Reputation: 51582
Another idea is to use make.unique
to make the names unique, and then use %in%
to create a logical vector and index the original one, i.e.
set1[!make.unique(set1) %in% make.unique(set2)]
#[1] "chair" "table"
Or make it a function,
f1 <- function(vec1, vec2){
vec1[!make.unique(vec1) %in% make.unique(vec2)]
}
f1(set1, set2)
Upvotes: 1
Reputation: 132969
set1 <- c("chair", "chair", "table")
set2 <- c("chair")
levels <- union(set1, set2)
set1 <- factor(set1, levels = levels)
set2 <- factor(set2, levels = levels)
rep(levels, table(set1) - table(set2))
#[1] "chair" "table"
Upvotes: 3