3

我有这个数据集

d1 = data.frame(PatID=c(1,1,1,2,2,4,1,2), 
                code1=c(1,2,3,1,2,7,2,8), 
                location=c('a','b','c','d','e','f','g','h'))

我想消除重复的行(on PatID)所以

  1. 每个唯一的我只有一行PatID
  2. 合并所有常见行的 code1 值,
  3. 保留任何匹配行的位置(对于第一行或最后一行 - 无关紧要)。

输出应该是:

PatID    code1    location 
1        1,2,3    a 
2        1,2,8    d 
4        7        f 

我尝试过不成功的聚合、ddply 甚至与 melt dcast 作斗争。我是一名前 unix 程序员,但对不熟悉。

4

2 回答 2

4

ddply工作得很好:

ddply(d1,.(PatID),
      summarise,
      code1 = paste(unique(code1),collapse = ','),
      location = location[1])

  PatID code1 location
1     1 1,2,3        a
2     2 1,2,8        d
3     4     7        f

哦好的。这是 data.table 版本:

d2 <- as.data.table(d1)
> d2[,list(code1 = paste(unique(code1),collapse = ','),location = location[1]),by = 'PatID']
   PatID code1 location
1:     1 1,2,3        a
2:     2 1,2,8        d
3:     4     7        f
于 2013-07-17T18:28:50.143 回答
1

只是为了确保不会完全忽略基本 R(或者让您欣赏这些类型问题的“plyr”和“data.table”的语法)......

两种选择:

选项 1:用于ave进行“聚合”并unique缩小输出

unique(within(d1, {
  code1 <- ave(code1, PatID, 
               FUN=function(x) paste(unique(x), collapse = ","))
  location <- ave(location, PatID, FUN=function(x) x[1])
}))
#   PatID code1 location
# 1     1 1,2,3        a
# 4     2 1,2,8        d
# 6     4     7        f

选项 2:aggregate一起merge工作

merge(
  aggregate(code1 ~ PatID, d1, 
          function(x) paste(unique(x), collapse = ",")),
  aggregate(location ~ PatID, d1, function(x) x[1]))
#   PatID code1 location
# 1     1 1,2,3        a
# 2     2 1,2,8        d
# 3     4     7        f

我能想到的最接近的纯aggregate解决方案如下:

aggregate(cbind(code1, as.character(location)) ~ PatID, d1, 
          function(x) cbind(paste(unique(x), collapse = ","),
                            as.character(x[1])))
#   PatID code1.1 code1.2    V2.1 V2.2
# 1     1   1,2,3       1 a,b,c,g    a
# 2     2   1,2,8       1   d,e,h    d
# 3     4       7       7       f    f

它为您提供了您感兴趣的所有信息,以及您不感兴趣的大量信息......

于 2013-07-17T18:52:47.060 回答