0

In R, I want to test if a pattern is present in a list, to replace an element located at the position in another list.

Let me take an example. My first list looks like this:

table 1:

     [,1]     [,2]    
[1,]ABBABBCA
[2,]ABBUCCCH

My second list looks like this:

     [,1]     [,2]    
[1,]KIGSPLOM
[2,]ANAMAKAM

I want to test the condition, if the pattern "KI" is present in my second list then replace the element at the same place in my first list.

In this case, KI is present in my second list in "KIGS" and I would replace "ABBA" by "KI". So in position [1,1] in both lists.

Is there a way to easily do that in Rand obtain the following list:

     [,1]     [,2]    
[1,]KI      BBCA
[2,]ABBUCCCH

  • 2
    Welcome to StackOverflow. Please take a look at these tips on how to produce a [minimum, complete, and verifiable example](http://stackoverflow.com/help/mcve), as well as this post on [creating a great example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Images of data are not very reproducible. – lmo Dec 16 '16 at 12:51
  • Thanks, but seems that HTML tables are not allowed so i edited the question. – Sylvain Le Barillec Dec 16 '16 at 14:07

1 Answers1

0

If I understand correctly your answer, a possible solution is using the command ifelse in relation with grepl. But, Do you have two matrix or two list? A list is a generic vector containing other objects, it's different from your example (read this site http://www.programcreek.com/2014/01/vector-array-list-and-data-frame-in-r/). Then:

The two matrix as examples:

   table1<-matrix(c("ABBA","BBCA","ABBU","CCCH"),nrow=2,ncol=2,byrow=TRUE)
   table2<-matrix(c("KIGS","BBCA","ABBU","CCCH"),nrow=2,ncol=2,byrow=TRUE)

table1
     [,1]   [,2]  
[1,] "ABBA" "BBCA"
[2,] "ABBU" "CCCH"

table2
     [,1]   [,2]  
[1,] "KIGS" "BBCA"
[2,] "ABBU" "CCCH"

I used a for loop with ifelse, conditional element selection, and grepl command as:

for(j in 1:ncol(table2)){
for(i in 1:nrow(table2)) { 
table2[i,j]<-ifelse(grepl("KI",table2[i,j])==TRUE,table1[i,j],table2[i,j])
}}

then we have table2 as:

table2
     [,1]   [,2]  
[1,] "ABBA" "BBCA"
[2,] "ABBU" "CCCH"
angeella
  • 126
  • 7
  • I note now the changes of question, then instead of having `table2[i,j]<-ifelse(grepl("KI",table2[i,j])==TRUE,table1[i,j],table2[i,j])`, you can put `table1[i,j]<-ifelse(grepl("KI",table2[i,j])==TRUE,"KI",table1[i,j])` – angeella Dec 16 '16 at 14:32
  • Thanks Angella. I checked and the 2 sets of data i want to "match" are Large Lists made of 1194 elements each. Each element is a chr [1:2, 1:2] – Sylvain Le Barillec Dec 16 '16 at 15:54
  • Try to do this `output <- matrix(unlist(table), ncol = 10, byrow = TRUE)` thanks to [link](http://stackoverflow.com/questions/13224553/how-to-convert-a-list-to-a-matrix-more-efficiently-in-r) – angeella Dec 20 '16 at 10:44
  • The option `ncol` should be altered considering your specific case. – angeella Dec 20 '16 at 12:03