[英]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.