Many similar questions have been asked that relate to this problem (see here and here for examples). But none specifically answer my question.
In my data frame I have a column comprised of characters and NA
s. Im trying to sort this column into groups that are based on other columns in my data frame. For example, if my data looks like this:
library(dplyr)
dfTest <- tibble(
var = c("x1", NA, NA, "x4", NA, "x4", NA, NA, "x2", NA, NA, "x1", NA, NA, "x2", NA, NA,
"x4", NA, "x4", NA, NA, 'x5', NA, NA, 'x2', NA, NA, "x1", NA, "x2", NA, NA, 'x5', NA, NA),
nam = c(1,1,1,2,2,2,2,2,3,3,3,4,4,4,5,5,5,
1,1,1,1,1,2,2,2,3,3,3,4,4,4,4,4,5,5,5),
itr = c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)
)
> dfTest
# A tibble: 36 × 3
var nam itr
<chr> <dbl> <dbl>
1 x1 1 1
2 NA 1 1
3 NA 1 1
4 x4 2 1
5 NA 2 1
6 x4 2 1
7 NA 2 1
8 NA 2 1
9 x2 3 1
10 NA 3 1
11 NA 3 1
12 x1 4 1
13 NA 4 1
14 NA 4 1
15 x2 5 1
16 NA 5 1
17 NA 5 1
18 x4 1 2
19 NA 1 2
20 x4 1 2
21 NA 1 2
22 NA 1 2
23 x5 2 2
24 NA 2 2
25 NA 2 2
26 x2 3 2
27 NA 3 2
28 NA 3 2
29 x1 4 2
30 NA 4 2
31 x2 4 2
32 NA 4 2
33 NA 4 2
34 x5 5 2
35 NA 5 2
36 NA 5 2
>
The first thing I am trying to do is sort the var
column by the itr
column. But I want to retain the grouping seen in the nam
column. In other words, Im trying to sort by the group structures.
so, for example, my desired output would look like this:
> dfTest
A tibble: 36 × 3
var nam itr
<chr> <dbl> <dbl>
1 x1 1 1
2 NA 1 1
3 NA 1 1
4 x1 4 1
5 NA 4 1
6 NA 4 1
7 x2 3 1
8 NA 3 1
9 NA 3 1
10 x2 5 1
11 NA 5 1
12 NA 5 1
13 x4 2 1
14 NA 2 1
15 x4 2 1
16 NA 2 1
17 NA 2 1
18 x5 2 2
19 NA 2 2
20 NA 2 2
21 x5 5 2
22 NA 5 2
23 NA 5 2
24 x4 1 2
25 NA 1 2
26 x4 1 2
27 NA 1 2
28 NA 1 2
29 x1 4 2
30 NA 4 2
31 x2 4 2
32 NA 4 2
33 NA 4 2
34 x2 3 2
35 NA 3 2
36 NA 3 2
For clarification, in the above example, we can see that when itr = 1
we have grouped the var
column by the nam
column in order of the frequency of the groups (i.e., when itr = 1
the group containing x1, NA, NA
appeared the most often, followed by the group containing x2, NA, NA
etc).
Any suggestions as to how I could achieve this?