合并具有相同ID的行并删除重复的行

时间:2017-11-08 14:58:16

标签: r dataframe data.table

合并一些数据后,每个ID有多行。如果数据不同,我只想保留多个SAME ID。 NA值应被视为等于任何colwise数据点。

数据:

df <- structure(list(id = c(1L, 2L, 2L, 2L, 3L, 3L, 4L, 4L, 4L, 5L), 
    v1 = structure(c(1L, 1L, NA, 1L, 1L, 1L, 1L, NA, 1L, 1L), .Label = "a", class = "factor"), 
    v2 = structure(c(1L, 2L, 2L, 3L, 1L, 1L, 1L, 1L, NA, 1L), .Label = c("a", 
    "b", "c"), class = "factor"), v3 = structure(c(1L, 1L, 1L, 
    1L, 1L, 1L, NA, 2L, 2L, 1L), .Label = c("a", "b"), class = "factor")), .Names = c("id", 
"v1", "v2", "v3"), row.names = c(NA, -10L), class = "data.frame")

看起来像:

   id   v1   v2   v3
    1    a    a    a
    2    a    b    a
    2 <NA>    b    a
    2    a    c    a
    3    a    a    a
    3    a    a    a
    4    a    a <NA>
    4 <NA>    a    b
    4    a <NA>    b
    5    a    a    a

期望的输出:

   id   v1   v2   v3
    1    a    a    a
    2    a    b    a
    2    a    c    a
    3    a    a    a
    4    a    a    b
    5    a    a    a

如果存在data.table解决方案,则感到高兴。

2 个答案:

答案 0 :(得分:4)

使用data.table - 包的可能解决方案:

library(data.table)
setDT(df)[, lapply(.SD, function(x) unique(na.omit(x))), by = id]

给出:

   id v1 v2 v3
1:  1  a  a  a
2:  2  a  b  a
3:  2  a  c  a
4:  3  a  a  a
5:  4  a  a  b
6:  5  a  a  a

答案 1 :(得分:1)

首先用相应的列值替换所有NA,然后找到唯一值

library(data.table)
dt<-as.data.table(df)
for (j in seq_len(ncol(dt)))
     set(dt,which(is.na(dt[[j]])),j,dt[[j]][1]) #please feel to change dt[[j]][1] to na.omit(dt[[j]])[1] . It is a tradeoff between performance and perfection
unique(dt)
 id v1 v2 v3
1:  1  a  a  a
2:  2  a  b  a
3:  2  a  c  a
4:  3  a  a  a
5:  4  a  a  a
6:  4  a  a  b
7:  5  a  a  a