首页 > 解决方案 > 在 data.table 中使用先前计算的值

问题描述

x.wantedMWE 中的 使用在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 是我失败的尝试。

在此处输入图像描述

标签: rdata.table

解决方案


如果我理解正确,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 问题中所示相同的图表。


推荐阅读