对每列唯一值的数量排序矩阵(或data.frame)

Pas*_*ten 4 sorting r matrix dataframe

如何在每列的唯一值总量上列reordera data.frame?举个例子:

var1 var2 var3
  1    1   1
  0    2   2
  1    3   3
  0    4   1
  1    5   2
Run Code Online (Sandbox Code Playgroud)

有没有办法像var2, var3, var1自动重新排序(因为唯一值的长度分别为5,3和2,或相反,2 3 5)?

在这种情况下,获得我们想要的东西并不困难,但在我的情况下,我有很多专栏.有没有办法自动进行这种类型的排序?

此外,我更愿意有一个解决方案matrix(除了data.frame),无论是否有列名称.

Aru*_*run 7

像这样的东西?

df[names(sort(sapply(df, function(x) length(unique(x))), decreasing = TRUE))]

#   var2 var3 var1
# 1    1    1    1
# 2    2    2    0
# 3    3    3    1
# 4    4    1    0
# 5    5    2    1
Run Code Online (Sandbox Code Playgroud)

如果你的输入是a matrix,那么:

m[, names(sort(apply(m, 2, function(x) 
       length(unique(x))), decreasing = TRUE))] 
Run Code Online (Sandbox Code Playgroud)

应该管用.

#      var2 var3 var1
# [1,]    1    1    1
# [2,]    2    2    0
# [3,]    3    3    1
# [4,]    4    1    0
# [5,]    5    2    1
Run Code Online (Sandbox Code Playgroud)

编辑:您在帖子中的示例似乎有列名称,但您在评论中给出的这个名称却没有.请确保正确生成示例.

X <- cbind(1, rnorm(10), 1:10)
Run Code Online (Sandbox Code Playgroud)

由于您不能指望列名称,因此您必须返回索引.试试这个(当然,如果你有列名,它会起作用):

m[, sort(apply(X, 2, function(x) 
         length(unique(x))), decreasing = TRUE, index.return = TRUE)$ix]
Run Code Online (Sandbox Code Playgroud)

  • +1 Argh,击败你16秒,但不是很好的答案! (2认同)

ags*_*udy 5

另一种解决方案order,

dat[,order(apply(dat,2,function(x) length(unique(x))),decreasing = TRUE)]
  var2 var3 var1
1    1    1    1
2    2    2    0
3    3    3    1
4    4    1    0
5    5    2    1
Run Code Online (Sandbox Code Playgroud)

现在,如果我们删除colnames,我们会得到好的结果,但会发出警告

 colnames(dat) <- NULL
 dat[,order(apply(dat,2,function(x) length(unique(x))),decreasing = TRUE)]
  NA NA NA
1  1  1  1
2  2  2  0
3  3  3  1
4  4  1  0
5  5  2  1
Run Code Online (Sandbox Code Playgroud)

编辑测试表现:

我测试了1000列的矩阵.2个解决方案时间具有可比性,略有增益order.

X <- matrix(rnorm(100*1000),ncol=1000,nrow=100)
Arun <- function() X[, sort(apply(X, 2, function(x) 
  length(unique(x))), decreasing = TRUE, index.return = TRUE)$ix]

AgStudy <- function()  X[,order(apply(X,2,function(x) length(unique(x))),decreasing = TRUE)]

library(microbenchmark)

microbenchmark(Arun(),AgStudy())

Unit: milliseconds
       expr      min       lq   median       uq      max
1 AgStudy() 28.04634 32.37105 34.73820 36.49930 129.6048
2    Arun() 31.15476 32.97180 36.24027 37.91584 132.3871
Run Code Online (Sandbox Code Playgroud)