vinsent paramanantham
vinsent paramanantham

Reputation: 951

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"

Upvotes: 0

Views: 62

Answers (1)

NicE
NicE

Reputation: 21425

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"

Upvotes: 2

Related Questions