I have the following data frame:
library(tidyverse)
dat <- structure(list(var1 = c(1L, 2L, 2L, 3L, 1L), var2 = structure(c(10L,
1L, 8L, 3L, 5L), .Label = c("b", "c", "f", "h", "i", "o", "s",
"t", "w", "x"), class = "factor"), var3 = c(7L, 5L, 5L, 8L, 5L
), var4 = structure(c(8L, 5L, 1L, 4L, 7L), .Label = c("b", "c",
"d", "e", "f", "h", "i", "w", "y"), class = "factor")), .Names = c("var1",
"var2", "var3", "var4"), row.names = c(NA, 5L), class = "data.frame")
dat
#> var1 var2 var3 var4
#> 1 1 x 7 w
#> 2 2 b 5 f
#> 3 2 t 5 b
#> 4 3 f 8 e
#> 5 1 i 5 i
What I want to do is to sort/arrange the var2
column
based on a predefined order:
my_order <- c('t','f','x','b','i')
The final desired result is this:
var1 var2 var3 var4
2 t 5 b
3 f 8 e
1 x 7 w
2 b 5 f
1 i 5 i
I'd like to do it under dplyr piping. How can I achieve that?
At best I can do is this:
> dat %>%
+ arrange(var2)
var1 var2 var3 var4
1 2 t 5 b
2 3 f 8 e
3 1 x 7 w
4 2 b 5 f
5 1 i 5 i
We can use arrange
with match
library(dplyr)
dat %>%
arrange(match(var2, my_order))
# var1 var2 var3 var4
#1 2 t 5 b
#2 3 f 8 e
#3 1 x 7 w
#4 2 b 5 f
#5 1 i 5 i
We can convert the column to a factor
with levels
specified as 'my_order' (but it doesn't change the type of the actual column)
library(dplyr)
dat %>%
arrange(factor(var2, levels = my_order))
# var1 var2 var3 var4
#1 2 t 5 b
#2 3 f 8 e
#3 1 x 7 w
#4 2 b 5 f
#5 1 i 5 i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With