2

I have a mapping function as follows,

sub.func <- function(x,y){
  if(agrepl(x,y)){
    return(x)
  }
  else{
    return(y)
  }
}

now I want to apply this to compare two lists of different size, say myList1 and myList2, such that for each element of myList1, sub.func will look for a match in myList2 and if yes will replace by the element of myList2. So that all elements of myList2 are mapped to. How can I achieve this without using loops? Any variant of apply functions can be used?

e.g.

myList1 <- c("a b", "c d", "e f")

myList2 <- c("1", "a b d", "d", "e f g h", "2 3 a c d", "c g")

desired output is same length as myList2 but mapped to myList1 wherever possible

output <- c("1", "a b", "d", "e f", "c d", "c g")
DonDyck
  • 1,451
  • 5
  • 20
  • 35
  • It would be helpful to include sample input and desired output just to make clear what you want and provide a simple way to test potential solutions. See [how to make a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Oct 24 '14 at 01:30
  • That will likely trigger a warning and give incorrect results because `agrepl` is a vectorized function. – Rich Scriven Oct 24 '14 at 01:32
  • Returns a vector result, I mean – Rich Scriven Oct 24 '14 at 01:40

1 Answers1

0

You could use the Reduce function for this

myList1 <- c("a b", "c d", "e f")
myList2 <- c("1", "a b d", "d", "e f g h", "2 3 a c d", "c g")

Reduce(function(vals, find) {vals[grep(find, vals)]<-find; vals}, myList1, myList2)
# [1] "1"   "a b" "d"   "e f" "c d" "c g"
MrFlick
  • 195,160
  • 17
  • 277
  • 295