7

我有这个数据框叫test

structure(list(event_type = structure(c(5L, 6L, 8L, 3L, 9L, 1L, 
7L, 4L, 10L, 2L), .Label = c("BLOCK", "CHL", "FAC", "GIVE", "GOAL", 
"HIT", "MISS", "SHOT", "STOP", "TAKE"), class = "factor"), hazard_ratio = c(0.909615543020822, 
1.3191464689192, 0.979677208703559, 1.02474605962247, 1.04722377755438, 
1.07656116782136, 1.01186162453814, 1.06021078216577, 0.972520062522276, 
0.915937088175971)), row.names = c(NA, -10L), class = "data.frame")

我想根据 重新排序event_typehazard_ratio所以我尝试了这个无济于事..

test %>% 
  mutate(event_type = as.character(event_type),
         event_type = fct_reorder(event_type, hazard_ratio))
4

1 回答 1

5

看起来这两种方法都对我的系统上的因素进行了重新排序

structure(list(event_type = structure(c(5L, 6L, 8L, 3L, 9L, 1L, 
7L, 4L, 10L, 2L), .Label = c("BLOCK", "CHL", "FAC", "GIVE", "GOAL", 
"HIT", "MISS", "SHOT", "STOP", "TAKE"), class = "factor"), hazard_ratio = c(0.909615543020822, 
1.3191464689192, 0.979677208703559, 1.02474605962247, 1.04722377755438, 
1.07656116782136, 1.01186162453814, 1.06021078216577, 0.972520062522276, 
0.915937088175971)), row.names = c(NA, -10L), class = "data.frame") -> test

我们将ggplot2用于验证,因为它使用factors 来订购轴的东西。

原来的:

ggplot(test, aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

在此处输入图像描述

好'ol基地R

mutate(test, event_type = reorder(event_type, hazard_ratio)) %>% 
  ggplot(aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

在此处输入图像描述

forcats

mutate(test, event_type = fct_reorder(event_type, hazard_ratio, .fun = identity)) %>% 
  ggplot(aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

在此处输入图像描述

于 2018-11-25T20:03:37.277 回答