Something like that?
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
If your input is matrix , then:
m[, names(sort(apply(m, 2, function(x) length(unique(x))), decreasing = TRUE))]
must work.
# var2 var3 var1 # [1,] 1 1 1 # [2,] 2 2 0 # [3,] 3 3 1 # [4,] 4 1 0 # [5,] 5 2 1
Edit: your example in the post seems to have column names, but this one that you gave in your comments does not work. Do not forget to give an example.
X <- cbind(1, rnorm(10), 1:10)
Since you cannot expect column names, you will need to return the indexes. Try this (this will work if you have column names or not, of course):
m[, sort(apply(X, 2, function(x) length(unique(x))), decreasing = TRUE, index.return = TRUE)$ix]
source share