根据值的子集重新排序整个 data.table

问题描述 投票:0回答:2

我正在尝试绘制一些分类数据,并且希望数据按数值排序。我可以使用

reorder
基函数对 data.table 重新排序,但我无法弄清楚如何仅基于数据的子集对整个列表进行重新排序。

dt <- data.table(Model = c(rep("M1", 4), rep("M2", 4)), 
           Var = rep(c("First", "Second", "Third", "Fourth"), 2),
           Value = c(1,3,4,5, 6,7,2,8))

ggplot(dt, aes(x = Model, y = Var)) +
  geom_tile(aes(fill = Value)) # Without reorder data are plotted alphabetically

dt[, Var := reorder(Var, Value, decreasing = TRUE)]

ggplot(dt, aes(x = Model, y = Var)) +
  geom_tile(aes(fill = Value))
# Reorder based on all Vars, but I want to reorder WITHIN M1

我想做的是仅基于 M1 进行重新排序。在这种情况下,应该将变量重新排序为“第一、第二、第三、第四”。

有没有一种方法可以完成此任务,而不涉及创建一个虚拟列,其中 M1 的变量在 M2 中重复?

我尝试过的各种子集尝试都不起作用:

dt[Model = "M1", Var := reorder(Var, Value, decreasing = TRUE), by = "M1"]
dt[, Var := reorder(Var, Value, decreasing = TRUE), by = "M1"]
setorder(dt, Value) # Does not reorder at all 
r ggplot2 plot data.table
2个回答
2
投票

一种选择是使用例如

ifelse
将非 M1 值设置为
NA
并使用
na.rm=TRUE
:

library(data.table)
library(ggplot2)

dt[, Var := reorder(Var,
  ifelse(Model == "M1", Value, NA),
  na.rm = TRUE, 
  decreasing = TRUE
)]

ggplot(dt, aes(x = Model, y = Var)) +
  geom_tile(aes(fill = Value))


0
投票

一个更简单、也许更标准的方法是按照所需的绘图顺序获取级别:

levels <- dt[Model=="M1"][order(-Value), Var]

然后在 ggplot() 调用中动态创建一个因子变量:

ggplot(dt, aes(x = Model, y = factor(Var, levels=levels) +
  geom_tile(aes(fill = Value)) + ylab("Var")
© www.soinside.com 2019 - 2024. All rights reserved.