R组重复值

R group repeating values

如果我正在处理这样的数据集

  Id     Index    Value
  1233   i1       Blue
  1233   i2       Blue
  1233   i3       Blue
  6545   i1       Red
  6545   i2       NA
  6545   i3       Black
  4177   i1       NA
  4177   i2       NA 
  4177   i2       NA 

如何通过仅保留 Id 重复值的一个实例来创建新数据集,例如 1233 和 4177,如下所示。

  Id     Index    Value
  1233   i        Blue
  6545   i1       Red
  6545   i2       NA
  6545   i3       Black
  4177   i        NA

我们可以使用distinct

library(dplyr)
distinct(df1, Id, Value, .keep_all = TRUE)
#    Id Index Value
#1 1233    i1  Blue
#2 6545    i1   Red
#3 6545    i2  <NA>
#4 6545    i3 Black
#5 4177    i1  <NA>

或使用base R

df1[!duplicated(df1[c('Id', 'Value')]),]

数据

df1 <- structure(list(Id = c(1233L, 1233L, 1233L, 6545L, 6545L, 6545L, 
4177L, 4177L, 4177L), Index = c("i1", "i2", "i3", "i1", "i2", 
"i3", "i1", "i2", "i2"), Value = c("Blue", "Blue", "Blue", "Red", 
NA, "Black", NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-9L))

也许unique + rownames可以帮到你

df[as.numeric(rownames(unique(df[-2]))),]

这样

    Id Index Value
1 1233    i1  Blue
4 6545    i1   Red
5 6545    i2  <NA>
6 6545    i3 Black
7 4177    i1  <NA>

数据

df <- structure(list(Id = c(1233L, 1233L, 1233L, 6545L, 6545L, 6545L, 
4177L, 4177L, 4177L), Index = c("i1", "i2", "i3", "i1", "i2", 
"i3", "i1", "i2", "i2"), Value = c("Blue", "Blue", "Blue", "Red", 
NA, "Black", NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-9L))

您可以使用 data.table 包及其 unique 方法的 by 参数:

library(data.table)
unique(setDT(df), by = c("Id", "Value"))
#       Id  Index  Value
# 1:  1233     i1   Blue
# 2:  6545     i1    Red
# 3:  6545     i2   <NA>
# 4:  6545     i3  Black
# 5:  4177     i1   <NA>