【问题标题】:R function that drops columns according column value and primary keys?根据列值和主键删除列的R函数?
【发布时间】:2020-02-07 13:20:24
【问题描述】:

目前我有一个已编译的数据框,因此对于相同的项目代码,有固定和变化的变量。例如:

..主键..b...... c.
1. 1234........苹果..梨
2. 1234........苹果..橙
3. 5678........浆果..酸橙
4. 5679........orange.apple
5. 5679........orange.apple

在这种情况下,尽管 c 列具有相同的主键 #1234,但 line1 和 line2 的列 c 具有不同的变量,因此应删除 c 列。 有什么方法可以在不对列名进行硬编码的情况下做到这一点?

【问题讨论】:

    标签: r


    【解决方案1】:

    使用dplyr,我们可以使用summarize_all()找到需要删除的列:

    library(dplyr)
    
    df <- tibble(key = c(1, 1, 2, 3, 3),
                b = c("a", "a", "b", "c", "c"),
                c = c("p", "o", "l", "a", "a"))
    
    drop_cols <- df %>%
      group_by(key) %>%
      summarize_all(~ any(. != .[1])) %>%
      select(-key) %>%
      select_if(any) %>%
      colnames()
    
    df %>% select(- one_of(drop_cols))
    

    【讨论】:

      【解决方案2】:

      dplyr 的一种方法是为每个 primary 键计算每列中不同元素的数量。然后我们 select 列,其中每个 primary 键只有一个唯一值。

      library(dplyr)
      
      df %>%
        select(df %>%
                group_by(primary) %>%
                mutate_at(vars(-group_cols()), n_distinct) %>%
                select_if(~all(. == 1)) %>% 
                names)
      
      #   primary      b
      #1    1234  apple
      #2    1234  apple
      #3    5678  berry
      #4    5679 orange
      #5    5679 orange
      

      数据

      df <- structure(list(primary = c(1234L, 1234L, 5678L, 5679L, 5679L), 
      b = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("apple", 
      "berry", "orange"), class = "factor"), c = structure(c(4L, 
      3L, 2L, 1L, 1L), .Label = c("apple", "lime", "orange", "pear"
      ), class = "factor")), class = "data.frame", row.names = c(NA,-5L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 2013-06-17
        • 2022-09-23
        相关资源
        最近更新 更多