Find similar elements between two lists and Replace with a corresponding elements
1
0
Entering edit mode
10.1 years ago

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 • 1.8k views
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

yes.

ADD REPLY
1
Entering edit mode

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

ADD REPLY
1
Entering edit mode
9.9 years ago
jeremy S ▴ 30

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.
ADD COMMENT

Login before adding your answer.

Traffic: 2659 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6