[英]working with list columns in r (data.table/dplyr)
我在listcolumns(20Gb)中組織了一個大型數據集。
1 - 我可以使用其他技巧來加速以下代碼嗎? Data.table似乎提供了兩倍的增長,但我認為還有其他技巧可以在類似的場景中使用。
2 - 除了saveRDS之外 - 還有其他更快的文件庫(vroom,fst和fwrite似乎不支持listcols)支持listcolumns嗎?
3-I嘗試了dt[,.(test=tib_sort[tib_sort[, .I[.N]], stringi::stri_sub(dt$ch, length = 5)],by=id)]
但它拋出的數字不正確維度錯誤。 是否有一個選項來執行by
使用listcolumn,並自動把它setDT和鍵/索引?
library(dplyr)
library(purrr)
library(data.table)
library(tictoc)
set.seed(123)
tib <-
tibble(id = 1:20000) %>% mutate(k = map_int(id, ~ sample(c(10:30), 1)))
tib <-
tib %>% mutate(tib_df = map(k, ~ tibble(
ch = replicate(.x, paste0(
sample(letters[1:24],
size = sample(c(10:20), 1)),
collapse = ""
)),
num = sample(1:1e10, .x,replace = F)
)))
help <- function(df) {
df <- df %>% top_n(1, num) %>% select(ch)
stringi::stri_sub(df, length = 5)
}
tic("purrr")
tib <- tib %>% mutate(result = map_chr(tib_df, help))
toc(log = T, quiet = T)
dt <- copy(tib)
setDT(dt)
tic("setDT w key")
dt[, tib_df := lapply(tib_df, setDT)]
dt[, tib_sort := lapply(tib_df, function(x)
setindex(x, "num"))]
toc(log = T, quiet = T)
tic("dt w key")
dt[, result_dt_key := sapply(tib_df, function(x) {
x[x[, .I[.N]], stringi::stri_sub(ch, length = 5)]
})]
toc(log=T, quiet = T)
tic.log(format = T)
[[1]]
[1] "purrr: 25.499 sec elapsed"
[[2]]
[1] "setDT w key: 4.875 sec elapsed"
[[3]]
[1] "dt w key: 12.077 sec elapsed"
1 purrr: 25.824 sec elapsed
2 setDT wo key: 2.97 sec elapsed
3 dt wo key: 13.724 sec elapsed
4 setDT w key: 1.778 sec elapsed
5 dt w key: 11.489 sec elapsed
6 dplyr,unnest: 1.496 sec elapsed
7 dt,I,unnest: 0.329 sec elapsed
8 dt, join, unnest: 0.325 sec elapsed
tic("dt, join, unnest")
b <- unnest(tib)
setDT(b)
unnest.J <- b[b[, .(num=max(num)), by = 'id'], on=c('id','num')][,r2:=stringi::stri_sub(ch,length=5)][]
toc(log=T)
res <- list(unnest.J$r2,tib2$result2,dt$result_dt_key,dt$result_dt,tib$result)
sapply(res,identical,unnest.I$r2)
[1] TRUE TRUE TRUE TRUE TRUE
所以 - 我想從中吸取的教訓是,盡管listcolumns看起來很容易被作為分析的數據結構,但它們更加流暢 。
在列表列上操作往往很慢,因為函數必須遍歷條目並且不能進行矢量化。 通常,對於unnest
列表列是有意義的:
tic("unnest")
tib2 <- tib %>%
tidyr::unnest(tib_df) %>%
group_by(id) %>%
top_n(1, num) %>%
mutate(result = stringi::stri_sub(ch, length = 5))
toc(log = T, quiet = T)
結果:
> tic.log(format = T)
[[1]]
[1] "purrr: 39.54 sec elapsed"
[[2]]
[1] "setDT w key: 10.7 sec elapsed"
[[3]]
[1] "dt w key: 19.19 sec elapsed"
[[4]]
[1] "unnest: 1.62 sec elapsed"
使用您的玩具數據,最終對象只是略有不同。 但如果有必要恢復原始表單,您可能希望執行以下操作:
tic("unnest+reattach")
tib2 <- tib %>%
tidyr::unnest(tib_df) %>%
group_by(id) %>%
top_n(1, num) %>%
mutate(result = stringi::stri_sub(ch, length = 5))
tib3 <- tib %>%
mutate(result = tib2$result[match(id, tib2$id)])
toc(log = T, quiet = T)
tic.log(format = T)[[5]]
[1] "unnest+reattach: 1.83 sec elapsed"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.