简体   繁体   中英

string operations in 'R' , Need to substract one string from other, find the A - B of list

> string1

[[1]]
[1] " DEV U 1"

[[2]]
[1] " DEV U 3G"

[[3]]
[1] " DEV U 4G"

[[4]]
[1] " THY 4M"

[[5]]
[1] " THY  5M"

[[6]]
[1] " THY 6G"

> string2

[[1]]
character(0)

[[2]]
[1] "3G"

[[3]]
[1] "4G"

[[4]]
[1] "4M"

[[5]]
[1] "5M"

[[6]]
[1] "6G"

> str(string1)
List of 6
 $ : chr " DEVE 1"

> str(string2)
List of 6
 $ : chr(0) 
 $ : chr "3G"

I wanted an output to get the strings as I wanted to substract both the list to remove the commons.

 [1] " DEV U 1"  

[[2]]
[1] " DEV U"

[[3]]
[1] " DEV U"

[[4]]
[1] " THY"

[[5]]
[1] " THY"

[[6]]
[1] " THY"

If you need to do this element-wise you could use mapply :

string1 <- list("DEV U 1","DEV U 3G","DEV U 4G","DEV U 3G")
string2 <- list(character(0),"3G","4G","5G")

mapply(function(x,y){
  if(!identical(x,character(0)))
    sub(x,'',y)
  else
    y
  },string2,string1)

#[1] "DEV U 1"  "DEV U "   "DEV U "   "DEV U 3G"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM