r - 在这种情况下如何使用 rbindlist(data) 而不是 do.call(rbind, data)

标签 r dplyr data.table

library(dplyr)
library(data.table)
library(stringr)

test = c('a1b1', 'a2b2', 'a3b3')
result = rbind(c(1,1),
               c(2,2),
               c(3,3))
result
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
test2<-do.call(rbind,test %>% str_split('a'))
test3<-do.call(rbind,test2 %>% .[,2] %>% str_split('b'))
test3
     [,1] [,2]
[1,] "1"  "1" 
[2,] "2"  "2" 
[3,] "3"  "3" 
  1. do.call(rbind, data) 不等于 rbindlist(data) 吗? data.table::rbindlist 不起作用。如果我想使用rbindlist,我该怎么办?
rbindlist(test %>% str_split('a'))
Error in rbindlist(test %>% str_split("a")) : 
  Item 1 of input is not a data.frame, data.table or list

最佳答案

如果您使用 tstrsplit 而不是 str_split,它们将已经是列而不是行,因此您可以使用 as.data.table而不是将它们rbind在一起。

test = c('a1b1', 'a2b2', 'a3b3')

library(data.table)
as.data.table(tstrsplit(tstrsplit(test, 'a')[[2]], 'b'))
#>        V1     V2
#>    <char> <char>
#> 1:      1      1
#> 2:      2      2
#> 3:      3      3

reprex package 于 2022 年 2 月 17 日创建(v2.0.1)

这会快得多,例如< 1 秒 vs 18 秒(如果向量有 10,000 个元素)。

test = c('a1b1', 'a2b2', 'a3b3')

library(data.table)
library(stringr)
library(bench)

test <- sample(test, 1e5, TRUE)

mark(
tstrsplit = 
  as.data.table(tstrsplit(tstrsplit(test, 'a')[[2]], 'b'))
,
str_split = {
  test2 <- rbindlist(test %>% str_split("a") %>% lapply(., function(x)
  as.data.table(t(x))))
  
  rbindlist(as.matrix(test2) %>% .[,2] %>% str_split("b") %>% lapply(., function(x)
  as.data.table(t(x))))
}
)
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 tstrsplit   134.8ms  138.7ms    7.16      9.54MB     1.79
#> 2 str_split     18.8s    18.8s    0.0532    3.11GB     2.66

reprex package 于 2022 年 2 月 17 日创建(v2.0.1)

关于r - 在这种情况下如何使用 rbindlist(data) 而不是 do.call(rbind, data),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71167713/

相关文章:

r - 如何使用 R 个性化时间线?

r - 无法将变量通过管道传递到级别

r - 如何使用 databricks 让 dplyr::summarize_all 在 SparkDataFrame 上工作?

r - 财务数据 - R 数据表 - 按条件分组

r - data.table 按组删除基于滞后值的行

r - 检查软件包版本是否达到或超过某个点

R 错误 : could not find function "select"

R: 一个 "tidy"版本的函数比原来的慢很多,我想知道为什么

r - 将表应用于向量列表并将其聚合

r - 如何检查矩阵或数据框中是否存在列?