【问题标题】:Remove the rows that have the same column A value but different column B value from df (but not vice-versa) in R从 R 中的 df 中删除具有相同 A 列值但 B 列值不同的行(反之亦然)
【发布时间】:2015-01-24 19:24:57
【问题描述】:

我正在尝试删除在我的数据框的“lan”列中具有相同值但在我的“id”列中具有不同值的所有行(反之亦然)。

使用示例数据集:

require(dplyr)
t <- structure(list(id = c(1L, 2L, 2L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 
                           4L), lan = structure(c(1L, 2L, 3L, 4L, 4L, 5L, 5L, 5L, 6L, 1L, 
                                                  7L), .Label = c("a", "b", "c", "d", "e", "f", "g"), class = "factor"), 
                    value = c(0.22988498, 0.848989831, 0.538065821, 0.916571913, 
                              0.304183372, 0.983348167, 0.356128559, 0.054102854, 0.400934593, 
                              0.001026817, 0.488452667)), .Names = c("id", "lan", "value"
                              ), class = "data.frame", row.names = c(NA, -11L))
t

我需要删除第 1 行和第 10 行,因为它们具有相同的 lan (a) 但不同的 id。

我尝试了以下方法,但没有成功:

a<-t[(!duplicated(t$id)),]
c<-a[duplicated(a$lan)|duplicated(a$lan, fromLast=TRUE),]
d<-t[!(t$lan %in% c$lan),]

感谢您的帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

    还有一个使用dplyr的替代方法:

    t2 <- t %>% 
      group_by(lan,id) %>%
      summarise(value=sum(value)) %>%
      group_by(lan) %>%
      summarise(number=n()) %>%
      filter(number>1) %>%
      select(lan)
    
    > t[!t$lan %in% t2$lan ,]
       id lan      value
    2   2   b 0.84898983
    3   2   c 0.53806582
    4   3   d 0.91657191
    5   3   d 0.30418337
    6   4   e 0.98334817
    7   4   e 0.35612856
    8   4   e 0.05410285
    9   4   f 0.40093459
    11  4   g 0.48845267
    

    【讨论】:

    • @akrun 非常感谢 Akrun。你无法想象我对你的解决方案说了多少次同样的话:)。我想我还是会打字谢谢cmets!您的解决方案非常出色且快速!
    • 很高兴帮助了艾丽西亚! :)
    • 使用@akrun 代码:>indx1 indx2 d暗淡(d) [1] 3936971 28
    • 使用@LyzanderR 代码:>data$value t2 % group_by(LAN,Patient.ID) %>% summarise(value=sum(value)) %> % group_by(LAN) %>% summarise(number=n()) %>% filter(number>1) %>% select(LAN) >d2dim(d2) [1] 3912020 29
    • 由于某种原因,您提出的解决方案对我来说不会产生相同的结果。我的数据集:dim(data) [1] 3936979 28
    【解决方案2】:

    您可以在“lan”上使用duplicated,以获取所有重复元素的逻辑索引,将两列重复相同('id','lan'),以获取不重复的元素,检查这些元素中的哪些元素在两种情况下都是 TRUE,否定和子集。

    indx1 <-  with(t, duplicated(lan)|duplicated(lan,fromLast=TRUE))
    indx2 <- !(duplicated(t[1:2])|duplicated(t[1:2],fromLast=TRUE))
    t[!(indx1 & indx2),]
    #   id lan      value
    #2   2   b 0.84898983
    #3   2   c 0.53806582
    #4   3   d 0.91657191
    #5   3   d 0.30418337
    #6   4   e 0.98334817
    #7   4   e 0.35612856
    #8   4   e 0.05410285
    #9   4   f 0.40093459
    #11  4   g 0.48845267
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 2021-01-25
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多