Test if a pattern is present in a list ; If Yes replace an element in another list

76 views Asked by At

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

1

There are 1 answers

4
angeella On

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"