Given n
columns, I'd like the first column to be in descending order, until a cutoff is reached and then the second column would be ordered, and so on. It's a little tricky to explain, so here's an example for the most simple case, with two columns:
df <- structure(list(x = c(0.92, 0.9, 0.9, 0.88, 0.86, 0.52, 0.35, 0.28, 0.02, -0.03,
-0.02, -0.06, -0.06, -0.01, -0.01, 0.01, -0.03, -0.03, 0.01, 0.05, -0.01),
y = c(0.03, -0.01, -0.03, 0, 0.02, 0.01, -0.08, 0.04, 0.71, 0.71, 0.69, 0.57,
0.55, 0.52, 0.4, -0.37, 0.37, 0.36, -0.34, -0.33, -0.32)),
.Names = c("x", "y"), row.names = c(NA, 21L), class = "data.frame")
After ordering, df
looks like this:
df[with(df, order (-abs(df$x), -abs(df$y))),]
x y
1 0.92 0.03
3 0.90 -0.03
2 0.90 -0.01
4 0.88 0.00
5 0.86 0.02
6 0.52 0.01
7 0.35 -0.08
8 0.28 0.04
12 -0.06 0.57
13 -0.06 0.55
20 0.05 -0.33
10 -0.03 0.71
17 -0.03 0.37
18 -0.03 0.36
9 0.02 0.71
11 -0.02 0.69
14 -0.01 0.52
15 -0.01 0.40
16 0.01 -0.37
19 0.01 -0.34
21 -0.01 -0.32
Only, column x
is ordered, as expected. However, if I wanted to institute a cutoff of .32
, where variables in the first column are arranged in descending order until the value < .32, whereupon it switches to ordering the second column, how might I do this?
I can do it by assigning NA
to values < .32, but I need to keep all the values, just order them in a similar way!
df.na<-df
df.na[abs(df.na)<.32]<-NA
df.na[with(df.na, order (-abs(df.na$x), -abs(df.na$y))),]
x y
1 0.92 NA
2 0.90 NA
3 0.90 NA
4 0.88 NA
5 0.86 NA
6 0.52 NA
7 0.35 NA
9 NA 0.71
10 NA 0.71
11 NA 0.69
12 NA 0.57
13 NA 0.55
14 NA 0.52
15 NA 0.40
16 NA -0.37
17 NA 0.37
18 NA 0.36
19 NA -0.34
20 NA -0.33
21 NA -0.32
8 NA NA
The solution will end up being used on a df with 10+ columns, so scalability is an issue!