匹配字符和顺序

时间:2018-08-02 06:43:54

标签: r char match

如果我有

之类的数据
idx<-c("1_1_2015_0_00_00","1_1_2015_0_10_00","1_1_2015_0_30_00","1_1_2015_0_40_00","1_1_2015_0_60_00","1_1_2015_0_80_00")
rr<-c(2,3,4,1,5,6)
no<-seq(1,6)
dat<-data.frame(no,idx,rr)

然后我要与标准索引配对

id<-c("1_1_2015_0_00_00","1_1_2015_0_10_00","1_1_2015_0_20_00","1_1_2015_0_30_00","1_1_2015_0_40_00","1_1_2015_0_50_00","1_1_2015_0_60_00","1_1_2015_0_70_00","1_1_2015_0_80_00")

所以我有诸如此类的缺失数据索引的等级

  no              idx  rr
1  1 1_1_2015_0_00_00  2
2  2 1_1_2015_0_10_00  3
3  NA              NA  NA
4  3 1_1_2015_0_30_00  4
5  4 1_1_2015_0_40_00  1
6  NA              NA  NA
7  5 1_1_2015_0_60_00  5
8  NA              NA  NA
9  6 1_1_2015_0_80_00  6

如何获取?

1 个答案:

答案 0 :(得分:0)

您可以使用match

dat[match(id, dat$idx), ]
#     no              idx rr
#1     1 1_1_2015_0_00_00  2
#2     2 1_1_2015_0_10_00  3
#NA   NA             <NA> NA
#3     3 1_1_2015_0_30_00  4
#4     4 1_1_2015_0_40_00  1
#NA.1 NA             <NA> NA
#5     5 1_1_2015_0_60_00  5
#NA.2 NA             <NA> NA
#6     6 1_1_2015_0_80_00  6

match(id, dat$idx)返回

#[1]  1  2 NA  3  4 NA  5 NA  6

,我们使用此向量选择dat的行。