如何根据R中的另一个变量按ID合并两个数据集

时间:2015-01-24 20:07:57

标签: r merge

我想合并两个带ID的数据集。 Data2是较大数据集(data1)的子集,它是通过删除在data1中标记为1的ID来创建的。在样本数据中,两个数据集具有相同的ID,直到ID 426.对于ID 427,当第一个数据中的标记为1时,第二个数据删除该条目并继续顺序ID。因此,第二数据中的Id 427在第一数据中是428。同样,第二个数据中的ID 1865在第一个中是1867。我怎么能合并这些数据集?我在线提供了一个样本数据。第一个数据有变量id,date和tag,而第二个数据有id1和date1

> dput(data1)
structure(list(id = c(426L, 427L, 428L, 429L, 430L, 431L, 432L, 
1865L, 1866L, 1867L, 1868L, 1869L, 1870L, 1871L, 2388L, 2389L, 
2390L, 2391L, 2965L, 2966L, 2967L, 2968L, 2969L, 2970L), date = structure(c(11250, 
7308, 12436, 9919, 13372, 9526, 8232, 7306, 9872, 7398, 10332, 
12967, 14288, 14053, 7311, 10268, 7772, 14477, 7309, 10228, 8917, 
10216, 10873, 8065), class = "Date"), tag = c(0L, 1L, 0L, 0L, 
0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 
0L, 0L, 0L, 0L)), datalabel = "", time.stamp = "24 Jan 2015 22:01", .Names = c("id", 
"date", "tag"), formats = c("%8.0g", "%tdDD_mon_CCYY", "%8.0g"
), types = c(252L, 254L, 251L), val.labels = c("", "", ""), var.labels = c("", 
"", ""), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", 
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", 
"20", "21", "22", "23", "24"), version = 12L, class = "data.frame")
> 



> dput(data2)
structure(list(id1 = c(426L, 427L, 428L, 429L, 430L, 431L, 432L, 
1865L, 1866L, 1867L, 1868L, 1869L, 1870L, 1871L, 2388L, 2389L, 
2390L, 2391L, 2965L, 2966L, 2967L, 2968L, 2969L, 2970L), date1 = structure(c(11250, 
12436, 9919, 13372, 9526, 8232, 13787, 7398, 10332, 12967, 14288, 
14053, 11620, 11426, 14477, 11464, 9029, 11875, 10873, 8065, 
11233, 13848, 10204, 9535), class = "Date")), datalabel = "", time.stamp = "24 Jan 2015 22:00", .Names = c("id1", 
"date1"), formats = c("%8.0g", "%tdDD_mon_CCYY"), types = c(252L, 
254L), val.labels = c("", ""), var.labels = c("", ""), row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
), version = 12L, class = "data.frame")

2 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

data <- sqldf("select a.*, b.* from data1 a left join data2 b on a.date = b.date1")

或可能:

data <- sqldf("select a.id, a.date from data1 a join data2 b on a.date = b.date1")

答案 1 :(得分:0)

至于我可以从你对其他帖子的评论中读到,你想从data1中选择那些标签为0的行。这可以用

来实现。
data2 <- data1[data1$tag == 0,]