I would like to reorder my numeric column according to the factor levels of group column. my toy data looks as following:
toy.df <- data.frame(group = c(rep("C",3), rep("B", 2),rep("A", 1)), num = c(rep(10, 3), rep(5,2), 20))
toy.df$group <- factor(toy.df$group, levels = c('B', 'A', 'C'))
toy.df$num <- factor(toy.df$num, levels = c('B', 'A', 'C'))
The last line of code is not working. Do you have any idea how I can set the levels of column num using levels of column group.
thanks
CodePudding user response:
Assuming you want to level order of num
to mirror the level order of group
, such that the levels of num
are 5, 20, 10 then you could sort your data frame by group
and then use forcats::fct_inorder
. This will assign the factor levels of num
in order of appearance:
library(tidyverse)
df <- toy.df %>%
arrange(group) %>%
mutate(num = fct_inorder(factor(num)))
levels(df$num)
[1] "5" "20" "10"
Note: this will change the order of your data frame.
You can also use fct_reorder
using a custom function to reorder num
that's based on group
:
df <- toy.df %>%
mutate(num = fct_reorder(factor(num), group, function(x) as.numeric(unique(x))))
Alternatively, you could sort the data and then pull out the unique values of num
which are ordered by group
and use that to assign the levels:
df <- toy.df %>%
mutate(num = factor(num, unique(arrange(toy.df, group)$num)))