根据r中的ID查找另一列中一列的值

时间:2017-07-12 09:18:36

标签: r which

我有一个数据框,每个ID都有多个条目。 ID具有引用号(NEW_REF)和旧引用号(OLD_REF)。我需要找到每个ID的最新参考编号,这意味着参考编号不在旧参考编号列中。

ID <- c(1,2,3,4,1,3,5,2,4,1,3,4)     
NEW_REF <- c("TS101","TS253","TS565","TS789","TD123","TS101","TD367","TH152","TD123","TF908","TD256","TS898")
OLD_REF <- c("TD123","TH152","TS101","TD123","TF908","TD256","TG232","TR142","TS898","TR268","TB496","TD969")
DF <- data.frame(ID,NEW_REF ,OLD_REF )

DF$Active_ind <- NA
DF$Active_ind[which(DF$NEW_REF %in% DF$OLD_REF )] <-"N"    #if a reference number is in the old reference number column it is not active or not the most recent
DF$Active_ind[which(!(DF$NEW_REF %in% DF$OLD_REF ))] <-"Y"   #if a reference number is not in the old reference number column it is active or the most recent

    ID NEW_REF OLD_REF Active_ind
1   1   TS101   TD123          N
2   2   TS253   TH152          Y
3   3   TS565   TS101          Y
4   4   TS789   TD123          Y
5   1   TD123   TF908          N
6   3   TS101   TD256          N
7   5   TD367   TG232          Y
8   2   TH152   TR142          N
9   4   TD123   TS898          N
10  1   TF908   TR268          N
11  3   TD256   TB496          N
12  4   TS898   TD969          N

我的问题是ID 1有一个新的参考TS101(第1行),而ID 3有一个旧的参考TS101(第3行)。如果参考号不是唯一的,如何查看哪个参考号是最近的每个ID

我希望第1行在Active_ind列中有一个Y:

    ID NEW_REF OLD_REF Active_ind
1   1   TS101   TD123          Y
2   2   TS253   TH152          Y
3   3   TS565   TS101          Y
4   4   TS789   TD123          Y
5   1   TD123   TF908          N
6   3   TS101   TD256          N
7   5   TD367   TG232          Y
8   2   TH152   TR142          N
9   4   TD123   TS898          N
10  1   TF908   TR268          N
11  3   TD256   TB496          N
12  4   TS898   TD969          N

我知道有可能使用for循环,但我想避免它,因为我的数据集有超过40 000个不同的ID,并且在使用循环时变得非常耗时。

1 个答案:

答案 0 :(得分:0)

我们可以使用dplyrID对其进行分组,然后检查NEW_REFOLD_REF中的值是否存在,并相应地为其提供值。

library(dplyr)
DF %>%
   group_by(ID) %>%
   mutate(Active_Ind = ifelse(NEW_REF %in% OLD_REF, "N", "Y"))


#     ID NEW_REF OLD_REF Active_Ind
#   <dbl>  <fctr>  <fctr>      <chr>
#      1   TS101   TD123          Y
#      2   TS253   TH152          Y
#      3   TS565   TS101          Y
#      4   TS789   TD123          Y
#      1   TD123   TF908          N
#      3   TS101   TD256          N
#      5   TD367   TG232          Y
#      2   TH152   TR142          N
#      4   TD123   TS898          N
#      1   TF908   TR268          N
#      3   TD256   TB496          N
#      4   TS898   TD969          N