I want to subtract y from x, which means remove one \"A\", three \"B\" and one \"E\" from x, so xNew
will be c(\"A\", \"C\", \"A\",\"B\",\"D\")
. It
You can use the function pmatch
:
x[-pmatch(y,x)]
#[1] "A" "C" "A" "B" "D"
Edit
If your data can be strings of more than 1 character, here is an option to get what you want:
xNew <- unlist(sapply(x[!duplicated(x)],
function(item, tab1, tab2) {
rep(item,
tab1[item] - ifelse(item %in% names(tab2), tab2[item], 0))
}, tab1=table(x), tab2=table(y)))
Example
x <- c("AB","BA","C","CA","B","B","B","B","D","E")
y <- c("A","B","B","B","E")
xNew
# AB BA C CA B D
#"AB" "BA" "C" "CA" "B" "D"