Home > Mobile >  Groupby one column and rearrange another string column based on a vector of string in R
Groupby one column and rearrange another string column based on a vector of string in R

Time:12-20

For the following toy data dd, I try to groupby langue column and rearrange char column based on the order of vector char_order:

dd <- data.frame(langue = c('English', 'French', 'English', 'French'),
                 char = c('world', 'monde', 'hello', 'bonjour'), 
                 x = c(8, 3, 9, 9),
                 y = c(1, 1, 1, 2))
dd

char_order <- c('hello', 'world', 'bonjour', 'monde')
dd %>% 
  group_by(langue) %>% arrange(.by_group = TRUE)

Out:

  langue  char        x     y
  <chr>   <chr>   <dbl> <dbl>
1 English world       8     1
2 English hello       9     1
3 French  monde       3     1
4 French  bonjour     9     2

But I wish to get a result as follows:

  langue  char        x     y
  <chr>   <chr>   <dbl> <dbl>
1 English hello       9     1
2 English world       8     1
3 French  bonjour     9     2
4 French  monde       3     1

How could I achieve that in pipe (%>%) using dplyr or other packages? Sincere thanks.

CodePudding user response:

You may set factor levels

dd %>%
  mutate(char = factor(char, levels = char_order)) %>%
  group_by(langue) %>% arrange(char ,.by_group = TRUE)

  langue  char        x     y
  <chr>   <fct>   <dbl> <dbl>
1 English hello       9     1
2 English world       8     1
3 French  bonjour     9     2
4 French  monde       3     1
  • Related