删除r中另一列中具有相同id但值不同的行

时间:2018-03-01 15:46:52

标签: r

我有一个数据框如下:

id = c("a2887", "a2887", "a5511","a5511","a2806", "a1491", "a1491", "a4309", "a4309") 
plan = c("6V", "6V", "25HS", "50HS", "25HS", "250Mbps", "250Mbps", "15Mbps", "15Mbps") 
df = data.frame(id, plan)

看起来像:

   id    plan 
a2887      6V
a2887      6V
a5511    25HS
a5511    50HS
a2806    25HS
a1491 250Mbps
a1491 250Mbps
a4309  15Mbps
a4309  15Mbps

我想删除具有相同ID但在列计划中具有不同值的行,只保留具有唯一ID /计划匹配的行并创建一个新的数据框,如下所示:

   id    plan
a2887      6V
a2806    25HS
a1491 250Mbps
a4309  15Mbps

有没有优雅的方法来实现这一目标? 谢谢!

3 个答案:

答案 0 :(得分:4)

我们可以使用tidyverse。按照' id',filter分组' id'只有一个唯一的值来计划'并获取distinct

library(dplyr)
df %>%
   group_by(id) %>%
   filter(n_distinct(plan)==1) %>%
   distinct()
# A tibble: 4 x 2
# Groups: id [4]
#  id     plan   
#  <fctr> <fctr> 
#1 a2887  6V     
#2 a2806  25HS   
#3 a1491  250Mbps
#4 a4309  15Mbps 

答案 1 :(得分:1)

data.table解决方案:

library(data.table)
setDT(df)
df <- unique(df)
df[, idx := .N, by = id]
df <- df[!(idx > 1), ]
df[, idx := NULL]

     id    plan
1: a2887      6V
2: a2806    25HS
3: a1491 250Mbps
4: a4309  15Mbps

答案 2 :(得分:1)

基础R解决方案:

# split df into different groups by id after removing duplicates
df <- unique(df)
df <- split(df, df$id)

# keep those 'groups' with only a single row
df <- df[sapply(df, nrow) == 1]

# bind rows together
df <- do.call(rbind, df)