提问人:seansteele 提问时间:5/15/2023 更新时间:5/15/2023 访问量:80
有没有一种更快的方法可以根据另一列中的级别对列进行分解和重新调整?
Is there a quicker way to factor and relevel a column based on the levels in another column?
问:
我下面的代码可以工作,但我觉得我错过了一种更快地做到这一点的方法(即我不知道更好的函数)。当我根据另一列搜索重新调平的论坛时,我得到的只是答案——我已经通过一系列电话完成了——但我觉得有一个更优雅的解决方案。factor(metric, levels = c(...)
# Order of the week I would like to display in ggplot
week_order <- c('Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue' )
# Data
df <- tibble(metric = c(0, 8, 12, 18, 6, 12, 20),
label_day = c('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
legend_text = c('Off', 'ReEntry', 'Strength', 'Match 1', 'Recovery', 'Activation', 'Match 2'))
# Change `label_day` into a factor and order based on `week_order`
df <- df |>
mutate(label_day = factor(label_day, levels = week_order)) |>
arrange(label_day)
# Is there a more elegant way to do this ? -------------------------------------------------------
# Now that the df is in the correct order, pull out the order that `legend_text` is in to use in ggplot
legend_text_order <- df |>
distinct(legend_text) |>
pull()
# Change `legend_text` into a factor and order based on `legend_text_order`
df <- df |>
mutate(legend_text = factor(legend_text, levels = legend_text_order))
#-------------------------------------------------------------------------------------------------
# Plot
ggplot(df, aes(x = legend_text, y = metric)) +
geom_col()
答:
1赞
Ricardo Semião e Castro
5/15/2023
#1
您可以在一个管道中完成所有操作:
df <- df |>
mutate(label_day = factor(label_day, levels = week_order)) |>
arrange(label_day) |>
mutate(legend_text = factor(legend_text, levels = unique(legend_text)))
由于您实际上并不需要将 keep 作为一个因素,只需使用它的顺序来排列数据集,因此您可以进一步缩小它:label_day
df <- df |>
arrange(factor(label_day, levels = week_order)) |>
mutate(legend_text = factor(legend_text, levels = unique(legend_text)))
输出:
评论