根据另一个向量从数据框中选择行,包括重复

时间:2016-03-07 16:06:12

标签: r vector dataframe subset repeat

示例数据:

dates=seq(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-01-07 00:00:00"), by="day")
data=rnorm(7,1,2)
groupID=c(12,14,16,24,35,46,54)

DF=data.frame(Date=dates,Data=data,groupID=groupID)

BB=c(12,12,16,24,35,35)
DF[DF$groupID %in% BB,]

        Date       Data groupID
1 2015-01-01  4.4104202       12
3 2015-01-03  2.1557735       16
4 2015-01-04 -0.9880946       24
5 2015-01-05 -0.3396025       35

我需要根据矢量DF中与groupID列匹配的值来过滤数据框BB。但是,如果BB包含重复,则不会在结果中反映出来。

由于我的向量BB包含两个值1和5中的两个,因此输出应该是:

        Date       Data groupID
1 2015-01-01  4.4104202       12
1 2015-01-01  4.4104202       12
3 2015-01-03  2.1557735       16
4 2015-01-04 -0.9880946       24
5 2015-01-05 -0.3396025       35
5 2015-01-05 -0.3396025       35

有没有办法实现这个目标?如果可能,保持向量BB的顺序?

2 个答案:

答案 0 :(得分:1)

使用match()(或findInterval()):

DF[match(BB,DF$groupID),];
##           Date      Data groupID
## 1   2015-01-01 1.2199835      12
## 1.1 2015-01-01 1.2199835      12
## 3   2015-01-03 1.8141556      16
## 4   2015-01-04 0.2748579      24
## 5   2015-01-05 3.2030200      35
## 5.1 2015-01-05 3.2030200      35

(请注意,Data列不同,因为您使用rnorm()生成它而不先调用set.seed()。建议在任何代码示例中调用set.seed()你加入随机性,以便可以重现精确的结果。)

答案 1 :(得分:0)

您可以将BB转换为data.frame并使用merge()根据DF合并BBgroupID,具体而言:

dates=seq(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-01-07 00:00:00"), by="day")
groupID=c(12,14,16,24,35,46,54)
set.seed(1234)
data=rnorm(7,1,2)
DF=data.frame(Date=dates,Data=data,groupID=groupID)
BB=data.frame(groupID=c(12,12,16,24,35,35))

测试结果:

>merge(DF,BB,by="groupID")
  groupID       Date      Data
1      12 2015-01-01 -1.414131
2      12 2015-01-01 -1.414131
3      16 2015-01-03  3.168882
4      24 2015-01-04 -3.691395
5      35 2015-01-05  1.858249
6      35 2015-01-05  1.858249