jeudi 14 décembre 2017

Find if a string is contained within another string in R

I am trying to find if a string is contained in another string in a different dataframe. I am using if statements and for loops and I want to keep the structure as I have it but just can't find the correct syntax to use. An example of my first data frame is:

Route1
x y z
w x y z 
a b c
x y z

An example of my second data frame is:

Route2      Track
x y z        A
v w x y z    B
a b          C

Once I have found whether Route1 is contained in Route 2 I want to assign Route 1 the corresponding Track. Hence the final data frame for data frame 1 should be:

Route1   CalculatedTrack
x y z     A
w x y z   B
a b
x y z    A

The formula I current have is:

for (i in 1:nrow(df1)){
  for (j in 1:nrow(df2)){
    if((((grepl(df1$Route1[i], df2$Route2[j],perl = TRUE)==TRUE){
      df1$CalculatedTrack<-df2$Track[j]
    }
  }
}

Hence I want to loop through each row to see if Route1 is in any of Route2. Note that I have multiple columns in each data frame.

Thanks for any help

Aucun commentaire:

Enregistrer un commentaire