how to find the row number of a match string

Viewed 28

My data is like this

df<- structure(list(DES = c("AAAAA", "ABBBB", "BBDDD", "CHDDD", "NMHH", 
"YNNN", "UUUU", "IMMM", "TTSGG", "MHDDD", "IIKKKKK", "UDDDD", 
"AAAAA", "ABBBB"), Name = c("AB1", "TH1", "TH2", "HUA", "HUA1", 
"UMA", "YIN", "YIM", "IUMH", "YIMH", "YIH", "TH2", "AB1", "TH1"
), data = c(1.399260301, 1.435057306, 1.515715678, 1.157216398, 
1.452347714, 1.172466387, 1.16325675, 2.614138423, 0.895228818, 
1.571925745, 1.717242238, 1.572841664, 0.924094104, 1.59458932
), Exact = c(0.000536206, 0.000910058, 0.001145037, 0.00114666, 
0.001883335, 0.002365192, 0.002548559, 0.003406673, 0.004232483, 
0.005164572, 0.006269242, 0.006741774, 0.009565493, 0.009581586
), Class = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L)), class = "data.frame", row.names = c(NA, -14L))

my second data is like this

df2<-structure(list(DES = c("AAAAA", "ABBBB", "BBDDD", "CHDDD"), Name = c("AB1", 
"TH1", "TH2", "HUA")), class = "data.frame", row.names = c(NA, 
-4L))

when I match them is coming like this

  match(df$Name,df2$Name)
 [1]  1  2  3  4 NA NA NA NA NA NA NA  3  1  2

I want to know the row number of the one in class 2 , so I want to get the output of

12 
13
14
1 Answers

We may use which to wrap the logical vector to obtain the position index

i1 <- which(df$Name %in% df2$Name & df$Class == 2)

The position index of the other elements can be obtained with setdiff (instead of applying the condition again

setdiff(seq_along(df$Name), i1)
Related