PsychometStats
PsychometStats

Reputation: 380

How to use grep to search for strings in a loop

I have 2 data frames.

 #df1 dimensions [100,1]  
    item 
   "Like to cook"
   "Enjoy football"
    .............
   "Love to run"

 #df2 dimensions [3,1]
    item
   "Like to cook"
   "Enjoy football"
   "Love to run"

In df1 and df2, a single variable is sting. I am trying to use grep to take every element of df2, find respective matche in df1, and output a vector of row positions of where these matches are in df1. So the output would look something like [1] 1 2 100

   I tired the following, but for some reason I get the following  
   result: 

Integer(0).

I would be grateful for your help please.

 result = NULL
 for (i in 1:nrow(df2)) {
 result = grep(df2[,1], df1)
 }
 print(result)

Upvotes: 0

Views: 131

Answers (2)

Pablo Rod
Pablo Rod

Reputation: 669

Alternatively:

 result <- which(df1$a %in% df2$a)



        df1 <- data.frame(a = c("Like to cook", "Enjoy football", rep("any", 97),"Love to run"))
        df2 <- data.frame(a = c("Like to cook", "Enjoy football", "Love to run"))

Upvotes: 1

NelsonGon
NelsonGon

Reputation: 13319

Following your loop:

result = df
for (i in 1:nrow(df2)) {
  result[i,] = grep(df2[i,], df[,1])

}
result
         item
1           1
2           2
3           4
4 Love to run

Using a character vector:

result = character()
for (i in 1:nrow(df2)) {
  result[i] = grep(df2[i,], df[,1])

}
result

No loops:

 match(df2$item,df$item)
[1] 1 2 4

Upvotes: 1

Related Questions