【问题标题】:How to rank columns in terms of how much they increase number of unique rows? [closed]如何根据它们增加的唯一行数对列进行排名? [关闭]
【发布时间】:2015-09-16 16:06:56
【问题描述】:

假设我有一张尺寸为 N X M 的表格,我想找到一种系统的方法来根据列如何增加唯一行数来对列进行排名,最好是在 R 中。

【问题讨论】:

  • 请提供一个小的示例数据和基于此的预期输出。
  • 提问时最好提供reproducible example

标签: r dataframe unique dimensions


【解决方案1】:

试试这个例子:

#dummy data
df <- data.frame(a = c(1, 1, 1, 1),
                 b = c(1, 2, 3, 4),
                 c = c(1, 2, 2, 4))
#   a b c
# 1 1 1 1
# 2 1 2 2
# 3 1 3 2
# 4 1 4 4

#re order data.frame
df[,order(sapply(colnames(df), function(i) length(unique(df[,i]))),decreasing = TRUE)]
#   b c a
# 1 1 1 1
# 2 2 2 1
# 3 3 2 1
# 4 4 4 1

【讨论】:

    【解决方案2】:
    library(dplyr)
    
    test = data_frame(a = c(1, 1, 1),
                      b = c(1, 2, 2),
                      c = c(1, 2, 3))
    
    base = test %>% distinct
    
    nrow(base) - 
      names(base) %>% sapply(function(name)
        base %>%
          select_("-" %>% paste(name)) %>%
          distinct %>%
          nrow)
    

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多