r - 在 data.table 中使用先前计算的值
问题描述
x.wanted
MWE 中的 使用在x.wanted
上面的行上计算,然后从实际行中添加值。如何在 data.table 中完成?我以为shift
是这样,但给出了错误的结果。
x.wanted
是一种在具有不同条形宽度的图中分隔条形的方法。
library(data.table)
library(ggplot2)
dt <- data.table(x.group=c(rep(1L, 4L), rep(2L, 5L)),
x.width=c(2L, 4L, 2L, 6L, 4L, 2L, 4L, 6L, 2L),
x.sep=c(0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L),
x.wanted=c(1, 5, 9, 14, 2, 6, 10, 16, 21))
dt[, x.try.1:=x.width/2]
dt[, x.try.1:=shift(x=x.try.1, fill=0, type="lag") + x.sep + x.width/2, by=x.group]
p <- ggplot(dt, aes(x=x.wanted, y=5))
p <- p + geom_bar(aes(width=x.width), stat="identity", position="stack")
p <- p + facet_grid(x.group~., scales="free_x")
p
添加绘图以可视化想要的结果。x.try.1 是我失败的尝试。
解决方案
如果我理解正确,OP 想要定位条的中点。这可以通过使用cumsum()
函数(加号shift()
)来实现:
dt[, x.mid := cumsum(shift(x.width, fill = 0) + x.sep) + x.width/2, by = x.group][]
x.group x.width x.sep x.wanted x.try.1 x.mid 1: 1 2 0 1 1 1 2: 1 4 1 5 4 5 3: 1 2 1 9 4 9 4: 1 6 1 14 5 14 5: 2 4 0 2 2 2 6: 2 2 1 6 4 6 7: 2 4 1 10 4 10 8: 2 6 1 16 6 16 9: 2 2 1 21 5 21
的计算值x.mid
与 OP 一致x.wanted
。
另一种方法是绘制矩形而不是条形。这将使用 x 轴上的左右角点,这使得计算更简单,恕我直言:
dt[, x.min := cumsum(shift(x.width, fill = 0) + x.sep), by = x.group]
ggplot(dt, aes(xmin = x.min, xmax = x.min + x.width, ymin = 0, ymax = 5)) +
geom_rect() +
facet_grid(x.group ~ .)
这将创建与 OP 问题中所示相同的图表。
推荐阅读
- electron - 使用 phoenix-channels 和电子的网络工具中未显示 Websocket
- python - NEAT 实施 - 代码准备。创建多个对象的问题
- c# - Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“无法在空引用上执行运行时绑定”
- python - Python 内存使用行为 - Pandas 到 numpy
- database - 如何从 Heroku PostgreSQL 数据库创建 ERD?
- docker - docker vpn gateway 无需修改 ip 表
- php - Api 没有进入 Tawkto webhook
- azure-data-factory-2 - ADF DataFlow 表达式构建器中是否可以使用变量而不是值?
- python - 连接 USB 时自动运行 python 文件
- mysql - 有没有办法将此插入合并到选择查询中?