2

Lets say I have this DF

   country confirmed
1  Germany     10910
2 Slovakia      1269
3       US    175663

and I want order by COL "confirmed". How to do it on the fly within %>% ?

workaround is this

DF[order(DF$confirmed),]
   country confirmed
2 Slovakia      1269
1  Germany     10910
3       US    175663

But how to do it this way DF %>% order... ?

Andrew
  • 171
  • 1
  • 8

2 Answers2

2

In dplyr, there is arrange to do the ordering

library(dplyr)
DF <- DF %>%
    arrange(confirmed)

-output

DF
#    country confirmed
#2 Slovakia      1269
#1  Germany     10910
#3       US    175663

If we don't want to use DF <- use the %<>% from magrittr

library(magrittr)
DF %<>%
    arrange(confirmed)

Or in case, we wanted to use order, an option is to pull the column 'confirmed, do the order and slice the data based on that order

DF %>% 
    pull(confirmed) %>%
    order %>% 
    slice(DF, .)
#   country confirmed
#2 Slovakia      1269
#1  Germany     10910
#3       US    175663

Or another way is

DF %>% 
 pull(confirmed) %>% 
 order %>% 
 `[`(DF, .,)
#   country confirmed
#2 Slovakia      1269
#1  Germany     10910
#3       US    175663

data

DF <- structure(list(country = c("Germany", "Slovakia", "US"),
confirmed = c(10910L, 
1269L, 175663L)), class = "data.frame", row.names = c("1", "2", 
"3"))
akrun
  • 674,427
  • 24
  • 381
  • 486
  • great this works ! but excuse me you said that `If we don't want to assign back, use the %<>% from magrittr` but this is exatcly doing this ... assigning back – Andrew Dec 27 '20 at 23:15
  • @Andrew What I meant is the `df %>% arrange(confirmed)` only prints the output ordered into the console while keeping the `df` as the original one. It can changed only by assigning. The compound operator `%<>%` does the assignment as well. What I meant `if we don't want to assign back` is doing `df – akrun Dec 27 '20 at 23:17
  • 1
    ok, Thanks for help. Here is my working project http://webcovid19.online/ – Andrew Dec 27 '20 at 23:42
  • @Andrew it looks great! – akrun Dec 27 '20 at 23:44
1

Maybe you can try

> DF %>%
+   slice(order(confirmed))
   country confirmed
2 Slovakia      1269
1  Germany     10910
3       US    175663

Data

> dput(DF)
structure(list(country = c("Germany", "Slovakia", "US"), confirmed = c(10910L, 
1269L, 175663L)), class = "data.frame", row.names = c("1", "2",
"3"))
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45