数据表高效回收V2 [英] data.table efficient recycling V2

查看:84
本文介绍了数据表高效回收V2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的后续内容: data.table有效回收

This is a follow-up to this question : data.table efficient recycling

这里的区别是每行的未来年份不一定相同。.

我经常在data.table中使用回收,例如,当我需要对未来几年进行预测时。我会在以后的每一年重复我的原始数据。

I frequently use recycling in data.table, for exemple when I need to make projections future years. I repeat my original data fro each future year.

这可能会导致类似的情况:

This can lead to something like that :

library(data.table)
dt <- data.table(1:500000, 500000:1, rpois(500000, 240))
dt2 <- dt[, c(.SD, .(year = 1:V3)), by = 1:nrow(dt) ]

但是我经常不得不处理数百万行,并且比这个玩具示例中的列要多得多。时间增加了。尝试以下方法:

But I often have to deal with millions of lines, and far more columns than in this toy exemple. The time increases .. Try this :

library(data.table)
dt <- data.table(1:5000000, 5000000:1, rpois(5000000, 240))
dt2 <- dt[, c(.SD, .(year = 1:V3)), by = 1:nrow(dt) ]

我的问题是:是否可以更有效地实现这一目的?

My question is : is there a more efficient to achieve this purpose ?

谢谢您的帮助!

推荐答案

这是一个较快的实现,但是由于 data.table lapply 循环

This is a faster implementation, but still long due to the lapply loop in the data.table

dt2 <- data.table(
  rep(dt$V1, dt$V3),
  rep(dt$V2, dt$V3),
  rep(dt$V3, dt$V3),
  unlist(lapply(dt$V3, function(x){1:x}))
)

我希望这会有所帮助!

这篇关于数据表高效回收V2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆