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

后端 未结 1 990
自闭症患者
自闭症患者 2021-01-19 12:22

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

相关标签:
1条回答
  • 2021-01-19 12:52

    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"
    
    0 讨论(0)
提交回复
热议问题