我想遍历
data.table
,就像purrr::map
一样。虽然我能够通过将data.frame
转换为data.table
并在purrr::map
内部应用data.table
函数,但我想知道是否data.table
内置了某些东西,可以避免使用purrr::map
。我之所以问这个问题,是因为我不确定purrr::map
的性能在速度和所需内存方面如何。当处理大型数据集时,与dplyr
相比,我对dplyr
的速度和内存利用率感到失望。
我在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::map
和data.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
。非常感谢任何意见。
b <- Input_File[, .(sum=sum(L.Rev)), by=.(Zone,Fiscal.Year)]
吗?如果你真的想要分开部分,你可以使用split
-split(b[,-"Zone"], b$Zone)
。 - thelatemail