How to subtract a complete character vector with repeated characters from the other vector in R

血红的双手。 提交于 2019-12-01 20:40:31

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!