如何根据列数增加的唯一行数来对列进行排名?

时间:2015-09-16 16:06:56

标签: r dataframe unique dimensions

让我说我有一个尺寸为N X M的表,我想找到一种系统的方法来对列进行排名,就如何增加唯一行的数量而言,最好是在R中。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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)