R how order DF "on the fly" with %>%?

Viewed 73

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... ?

2 Answers

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"))

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"))
Related