![](/img/trans.png)
[英]Are you able to reference columns outside of .SD columns in an R data.table vectorized function?
[英]Perform rowwise non-vectorized function on a combination of columns in a data.table (R)
我在 R (~200,000) 條目中有一個非常大的 data.table,我想對每一行執行非矢量化 function 。 這個 function 需要來自這個 data.table 的兩列的輸入。 一列的值鏈接到另一個列表,每個成員包含約 1,000,000 個數字。 這是mtcars
的簡化案例
#setup a fake list for my function call
gears <- mtcars %>% arrange(gear) %>% pull(gear) %>% unique
gear_lst <- lapply(gears, function(x){rnorm(1000000, mean = x**2, sd = x*2)}) %>% setNames(.,gears)
#make a mega data table
mega_mtcars <- sapply(mtcars, rep.int, times = 10000) %>% as.data.table
#this is the function I want to call
my_function <- function(x,y){
sum(x > gear_lst[[y]])
}
# rowwise call is low
out <- mega_mtcars %>% mutate(gear_c = as.character(gear)) %>% rowwise %>% mutate(out = my_function(mpg, gear_c))
我嘗試的一件事是為每個gear
條目添加一個嵌套的gear_lst
列,以便我能夠執行矢量化 function。 但是,由於列表很大,memory 未能創建這樣的數據結構。
更新:@akrun 提供了一些方法,我無法用我原來的 mega_mtcars 測試它們,因為它太大了。 我把它縮小了 100 倍,這是迄今為止的性能(它似乎沒有比原來的 rowwise 方法有任何改進):
#make a smaller mega_mtcars
mega_mtcars <- sapply(mtcars, rep.int, times = 100) %>% as.data.table
# use rowwise from dplyr
system.time(mega_mtcars %>% rowwise %>% mutate(out = my_function(mpg, as.character(gear))))
user system elapsed
8.086 2.860 10.941
# use Map with data.table
system.time(mega_mtcars[, out := unlist(Map(my_function, x = mpg, y = as.character(gear)))])
user system elapsed
7.843 2.815 10.654
# use dapply from collapse package
system.time(dapply(mega_mtcars[, .(mpg, gear)], MARGIN = 1, function(x) my_function(x[1], as.character(x[2]))))
user system elapsed
7.957 3.167 11.127
還有其他想法嗎?
使用data.table
,可以通過對行序列進行分組來實現rowwise
library(data.table)
mega_mtcars[, out := my_function(mpg, as.character(gear)) ,
by = 1:nrow(mega_mtcars)]
對 gear_lst 中的值進行排序有幫助嗎?
很好,一個具有挑戰性的問題,嗯
我也有一個問題:data.table 中的這段代碼是並行運行的嗎?
library(data.table)
mega_mtcars[, out := my_function(mpg, as.character(gear)) ,
by = 1:nrow(mega_mtcars)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.