r-使用purrr :::映射的等效词通过data.table迭代



我想像purrr::map一样,要通过data.table进行迭代。虽然我能够通过将data.frame转换为data.table内的CC_4来应用data.table函数,但我想知道data.table是否具有使用purrr::map的内置的东西。我之所以问这个,是因为我不确定purrr::map在所需的速度和内存方面的性能。与data.table相比,我对dplyr的速度和内存利用感到失望。

我研究了Stackoverflow,发现通过数据表线程在迭代上接受答案已使用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迭代。我会感谢任何想法。

管道数据表可以通过重复[]来很好地完成,例如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])

如果您想迭代列,则可能需要查看此解决方案

更新:我想可以没有导入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

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

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

最新更新