按照R

时间:2015-11-24 18:32:38

标签: r dataset duplicates criteria

嗨我很担心有关R中重复的问题。我已经四处寻找并且似乎没有找到任何帮助。我有一个像这样的数据集

x = data.frame( id = c("A","A","A","A","A","A","A","B","B","B","B"),
                StartDate = c("09/07/2006", "09/07/2006", "09/07/2006", "08/10/2006", 
                              "08/10/2006", "09/04/2007", "02/03/2011","05/05/2005", "08/06/2009", "07/09/2009", "07/09/2009"),
                EndDate = c("06/08/2006", "06/08/2006", "06/08/2006", "19/11/2006", "19/11/2006", "07/05/2007", "30/03/2011",
                            "02/06/2005", "06/07/2009", "05/10/2009", "05/10/2009"),
                Group = c(1,1,1,2,2,3,4,2,3,4,4),
                TestDate = c("09/06/2006", "08/09/2006", "08/10/2006", "08/09/2006", "08/10/2006", "NA", "02/03/2011",
                              "NA", "07/09/2009", "07/09/2009", "08/10/2009"),
                Code = c(4,4,4858,4,4858,NA,4,NA, 795, 795, 4)
              )

> x
   id  StartDate    EndDate Group   TestDate Code
1   A 09/07/2006 06/08/2006     1 09/06/2006    4
2   A 09/07/2006 06/08/2006     1 08/09/2006    4
3   A 09/07/2006 06/08/2006     1 08/10/2006 4858
4   A 08/10/2006 19/11/2006     2 08/09/2006    4
5   A 08/10/2006 19/11/2006     2 08/10/2006 4858
6   A 09/04/2007 07/05/2007     3         NA   NA
7   A 02/03/2011 30/03/2011     4 02/03/2011    4
8   B 05/05/2005 02/06/2005     2         NA   NA
9   B 08/06/2009 06/07/2009     3 07/09/2009  795
10  B 07/09/2009 05/10/2009     4 07/09/2009  795
11  B 07/09/2009 05/10/2009     4 08/10/2009    4

所以基本上我要做的是通过ID识别TestDate变量中的重复项。例如,08/09/2006和08/10/2006的日期似乎在同一个人中重复,但对于不同的组,我不希望相同的Testdate在ID中以不同的Group分组。选择要选择哪个TestDate的标准是对不同的组采用TestDate与StartDate和EndDate的天数差异,然后保持天数差异最小的那个。例如,关于日期08/10/2006我想保持第5行作为TestDate,与StartDate相比,与第3行中的相同差异相比。最后,我想得到像这样的数据集

> xfinal
   id  StartDate    EndDate Group   TestDate Code
1   A 09/07/2006 06/08/2006     1 09/06/2006    4
4   A 08/10/2006 19/11/2006     2 08/09/2006    4
5   A 08/10/2006 19/11/2006     2 08/10/2006 4858
6   A 09/04/2007 07/05/2007     3         NA   NA
7   A 02/03/2011 30/03/2011     4 02/03/2011    4
8   B 05/05/2005 02/06/2005     2         NA   NA
10  B 07/09/2009 05/10/2009     4 07/09/2009  795
11  B 07/09/2009 05/10/2009     4 08/10/2009    4

对此的任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

x$StartDate <- as.Date(x$StartDate,format="%d/%m/%Y")
x$EndDate <- as.Date(x$EndDate,format="%d/%m/%Y")
x$TestDate <- as.Date(x$TestDate,format="%d/%m/%Y")
x$Diff <- difftime(x$EndDate,x$StartDate,"days")

x <- x[order(x$id,x$Diff),]

x <- x[!duplicated(x[,c("id","TestDate")]),]
x$Diff <- NULL
x