【问题标题】:Keep rows which are not unique but have different labels in another column in R在 R 的另一列中保留不唯一但具有不同标签的行
【发布时间】:2021-04-08 12:51:29
【问题描述】:

我有一个名为“dataframe”的数据框

它有一列“曝光”,例如ABC、DEF、GHI 和一列红色和黄色的“标签”。它们可以在标记为“红色”的一行上,也可以在标记为“红色”的多行上,也可以在“黄色”和“红色”的多行上

Exposure   Label
ABC        yellow
DEF        yellow
GHI        red
GHI        red
GHI        red
JKL        yellow
DEF        red
ABC        yellow
ABC        red

如何提取多次但颜色不同的那些?所以在这里我想保留 ABC,因为它既是黄色又是红色,但失去 GHI,因为它们只是红色。

到目前为止,我只能保留那些非唯一的

both <- dataframe %>% group_by(Exposure) %>% filter(n()>1)

但不知道如何指定保留那些只有不同标签而不是相同标签的标签?

谢谢!

【问题讨论】:

    标签: r subset unique


    【解决方案1】:
    library(data.table)
    # Sample data
    DT <- fread("Exposure   Label
    ABC        yellow
    DEF        yellow
    GHI        red
    GHI        red
    GHI        red
    JKL        yellow
    DEF        red
    ABC        yellow
    ABC        red")
    
    # Filter based more than 1 unique Label by Exposure-group
    DT[, if(uniqueN(Label) > 1) .SD, by = Exposure]
    
    #    Exposure  Label
    # 1:      ABC yellow
    # 2:      ABC yellow
    # 3:      ABC    red
    # 4:      DEF yellow
    # 5:      DEF    red
    

    【讨论】:

    • 或者我们可以做setDT(dataframe)[, .SD[uniqueN(Label) &gt; 1], Exposure]
    【解决方案2】:

    n() 将给出组中的行数,n_distinct(Label) 将给出唯一值的计数。

    library(dplyr)
    dataframe %>% group_by(Exposure) %>% filter(n_distinct(Label)>1) %>% ungroup
    
    #  Exposure Label 
    #  <chr>    <chr> 
    #1 ABC      yellow
    #2 DEF      yellow
    #3 DEF      red   
    #4 ABC      yellow
    #5 ABC      red   
    

    【讨论】:

      【解决方案3】:

      您可以将两列合并为一个新列,然后使用唯一的子集。

      df$x <- paste(df$Exposure,df$Label)
      
      df <- df[!duplicated(df$x), ]
      
      

      一切顺利, 库尔特

      【讨论】:

        【解决方案4】:

        基本 R 选项

        subset(
          dataframe,
          ave(Label, Exposure, FUN = function(x) length(unique(x))) > 1
        )
        

        给予

          Exposure  Label
        1      ABC yellow
        2      DEF yellow
        7      DEF    red
        8      ABC yellow
        9      ABC    red
        

        【讨论】:

          猜你喜欢
          • 2018-08-09
          • 2017-02-14
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 1970-01-01
          • 2019-05-31
          • 2022-07-18
          相关资源
          最近更新 更多