Phil Roberts
Phil Roberts

Reputation: 85

Arrange all groups within df by order of first group in R

I have a dataframe which looks like this:

Groupnum Variables Freq
   1        shell     4 
   1        water     3
   1        elev      2
   2        elev      4
   2        shell     3
   2        water     2
   3        elev      4
   3        water     3
   3        shell     2

I wish to arrange 'Variables' in each group (specified by Groupnum) according to the variable order in group one, so that the df would appear like this:

 Groupnum Variables Freq
   1        shell     4 
   1        water     3
   1        elev      2
   2        shell     3
   2        water     2
   2        elev      4
   3        shell     2
   3        water     3
   3        elev      4

I tried to achieve this using the following code:

library(dplyr)
df2 = group_by(df, Groupnum) %>% arrange(df$Groupnum==1, Variables, .by_group = TRUE)

This executed without error but the order did not change. Does anyone have any suggestions how best to achieve this?

Upvotes: 1

Views: 121

Answers (2)

Daniel O
Daniel O

Reputation: 4358

in Base-R:

    do.call(rbind,lapply(split(df,df$Groupnum),function(x) x[order(match(x$Variables,c("shell","water","elev"))),]))

output:

    Groupnum Variables Freq
1.1        1     shell    4
1.2        1     water    3
1.3        1      elev    2
2.5        2     shell    3
2.6        2     water    2
2.4        2      elev    4
3.9        3     shell    2
3.8        3     water    3
3.7        3      elev    4

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

One dplyr and forcats solution could be:

df %>%
 arrange(Groupnum, fct_inorder(Variables))

  Groupnum Variables Freq
1        1     shell    4
2        1     water    3
3        1      elev    2
4        2     shell    3
5        2     water    2
6        2      elev    4
7        3     shell    2
8        3     water    3
9        3      elev    4

Upvotes: 1

Related Questions