This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Find similar elements between two lists and Replace with a corresponding elements

I have a list of probe ids as below:

> head(best)
[[1]]
[[1]][[1]]
[1] "204639_at"  "203440_at"   "242136_x_at" "231954_at"   "208388_at"  
[6] "205942_s_at" "203510_at"   "204639_at"  

[[2]]
[[2]][[1]]
[1] "204639_at"  "203510_at"   "231954_at" 
.... 

Then I have used this file:

> head(sym)
                x
204639_at     ADA
203440_at    CDH2
242876_at    AKT3
207078_at    MED6
208388_at   NR2E3
222161_at NAALAD2

> class(sym)
[1] "data.frame"

Then, I want to find alternative names ("ADA" "CDH2" "AKT3" "MED6" "NR2E3" "NAALAD2") in sym and replace existing with elements in best file. Does anyone have a hack? Thanks

find-replace r

Do you need to keep the nested lists structure of best?

Could you give the gist of the nested-list structure?

1 answer

You can do a lot of gsubs. Here is a function for multiple gsub, then just lapply it over your list.

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

New_best <- lapply(best, function(x) lapply(x, function(z) mgsub(rownames(sym),sym$x,z)))

# not sure how nested that list is, but this works for the example data you gave.

Log in to answer this question.