使用等效的purrr ::: map迭代data.table

时间:2017-12-21 03:41:36

标签: r dplyr data.table purrr

我希望迭代data.table,就像purrr::map一样。虽然我可以通过在data.table内将data.frame转换为data.table来应用purrr::map函数,但我想知道data.table是否具有内置的内容会导致使用purrr::map。我问这个是因为我不确定purrr::map在所需速度和内存方面的表现。与处理大型数据集时的dplyr相比,我对data.table的速度和内存利用率感到失望。

我研究了stackoverflow,发现Iterate through data tables线程上接受的答案使用了for循环。出于性能原因,我不是for循环的忠实粉丝。

此处的示例数据文件:

dput(Input_File)
structure(list(Zone = c("East", "East", "East", "East", "East", 
"East", "East", "West", "West", "West", "West", "West", "West", 
"West"), Fiscal.Year = c(2016, 2016, 2016, 2016, 2016, 2016, 
2017, 2016, 2016, 2016, 2017, 2017, 2018, 2018), Transaction.ID = c(132, 
133, 134, 135, 136, 137, 171, 171, 172, 173, 175, 176, 177, 178
), L.Rev = c(3, 0, 0, 1, 0, 0, 2, 1, 1, 2, 2, 1, 2, 1), L.Qty = c(3, 
0, 0, 1, 0, 0, 1, 1, 1, 2, 2, 1, 2, 1), A.Rev = c(0, 0, 0, 1, 
1, 1, 0, 0, 0, 0, 0, 1, 0, 0), A.Qty = c(0, 0, 0, 2, 2, 3, 0, 
0, 0, 0, 0, 3, 0, 0), I.Rev = c(4, 4, 4, 0, 1, 0, 3, 0, 0, 0, 
1, 0, 1, 1), I.Qty = c(2, 2, 2, 0, 1, 0, 3, 0, 0, 0, 1, 0, 1, 
1)), .Names = c("Zone", "Fiscal.Year", "Transaction.ID", "L.Rev", 
"L.Qty", "A.Rev", "A.Qty", "I.Rev", "I.Qty"), row.names = c(NA, 
14L), class = "data.frame")

以下是purrr::mapdata.table

的示例代码
UZone <- unique(Input_File$Zone)
FYear <- unique(Input_File$Fiscal.Year)
a<-purrr::map(UZone, ~ dplyr::filter(Input_File, Zone == .)) %>%
   purrr::map(~ data.table::as.data.table(.)) %>%
   purrr::map(~ .[,.(sum = sum(L.Rev)),by=Fiscal.Year])

我并不太关心输出,但我想知道哪些替代品可用于基于特定列迭代data.table。我很感激任何想法。

2 个答案:

答案 0 :(得分:1)

重复[],例如管道数据表可以很好地完成。 DT[][][]。对于列表,我认为magrittr没有其他选择。其余的可以通过链接lapply

来完成
library(data.table)
library(magrittr)

Input_File <- data.table(Input_File)

UZone <- unique(Input_File$Zone)
FYear <- unique(Input_File$Fiscal.Year)

lapply(UZone, function(x) Input_File[Zone==x]) %>% 
  lapply(function(x) x[,.(sum=sum(L.Rev)), by=Fiscal.Year])

如果您要迭代超过列,您可能需要查看this solution

更新:我想如果没有导入magrittr而没有$子集

,可能会有更清晰的解决方案
library(data.table)

Input_File <- data.table(Input_File)

by_zone_lst <- lapply(Input_File[,unique(Zone)], function(x) Input_File[Zone==x])
summary_lst <- lapply(by_zone_lst, function(y) y[,.(sum=sum(L.Rev)), by=Fiscal.Year])

summary_lst

答案 1 :(得分:1)

我不确定问题的背后是什么,但我更喜欢

library(data.table)
setDT(Input_File)[, .(sum = sum(L.Rev)), by = .(Zone, Fiscal.Year)]
   Zone Fiscal.Year sum
1: East        2016   4
2: East        2017   2
3: West        2016   4
4: West        2017   3
5: West        2018   3

OP的方法将a作为

返回
[[1]]
   Fiscal.Year sum
1:        2016   4
2:        2017   2

[[2]]
   Fiscal.Year sum
1:        2016   4
2:        2017   3
3:        2018   3