r - 在 data.table 中按组绘制

标签 r data.table

我有个人级别的数据,我试图按组动态总结结果。

例子:

set.seed(12039)
DT <- data.table(id = rep(1:100, each = 50),
                 grp = rep(letters[1:4], each = 1250),
                 time = rep(1:50, 100),
                 outcome = rnorm(5000))

我想知道绘制组级摘要的最简单方法,其数据包含在:
DT[ , mean(outcome), by = .(grp, time)]

我想要类似的东西:
dt[ , plot(mean(outcome)), by = .(grp, time)]

但这根本行不通。

我赖以生存的可行选项(可以很容易地循环)是:
plot(DT[grp == "a", mean(outcome), by = time])
lines(DT[grp == "b", mean(outcome), by = time])
lines(DT[grp == "c", mean(outcome), by = time])
lines(DT[grp == "d", mean(outcome), by = time])

(添加了颜色等参数,为简洁起见不包括在内)

这让我觉得这不是最好的方法——给定 data.table处理组的技巧,难道没有更优雅的解决方案吗?

其他来源已将我指向 matplot但我看不到直接的使用方法——我需要 reshape DT , 有没有简单的reshape那会完成工作吗?

最佳答案

基地 R 使用 matplot 的解决方案和 dcast

dt_agg <- dt[ , .(mean = mean(outcome)), by=.(grp,time)]
dt_cast <- dcast(dt_agg, time~grp, value.var="mean")
dt_cast[ , matplot(time, .SD[ , !"time"], type="l", ylab="mean", xlab="")]
# alternative:
dt_cast[ , matplot(time, .SD, type="l", ylab="mean", xlab=""), .SDcols = !"time"]

结果:
enter image description here

关于r - 在 data.table 中按组绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28400446/

相关文章:

r - Shiny 的动态 selectizeInput

r - 使用 dplyr 拟合多个 nls 函数

r - 将数据帧列表转换为 R 中的单个数据帧

r - 通过参数连接 data.table

r - 在数据帧的每一行上向量化函数的有效方法

R:使用 LaF(快速读取固定列宽数据)和 SAScii(解析 SAS 字典以获取导入说明)

r - fread{data.table} 中的错误

r - 我使用plyr对吗?我似乎使用了太多的内存

r - 在 R 中用 data.table 对许多列求和,删除 NA

r - 将每个组与 data.table 中的每个其他组进行比较