数字和索引向量到data.table

时间:2015-12-22 19:29:19

标签: r data.table

将以下向量与每个数字的索引一起放入data.table的最佳方法是什么?

nVector <- c("20 37", "38 23", "39 48", "45 76", "65 44", "86 95 80")

这是我拥有的,有更好的方法吗?

vLength <- unname(sapply(nVector, function(x) length(unlist( strsplit(x, " "))) ))
vSeq <- seq(1, length(vLength))
vPosition <- vector("list", length(vLength))

for(i in 1:length(vLength))
{
  vPosition[[i]] <- rep(vSeq[i], vLength[i])
}

DT <- data.table(index = unlist(vPosition),
                 value = unlist(strsplit(nVector, " ")))

注意:向量的长度约为125k,并且有大约2000万个值。

2 个答案:

答案 0 :(得分:9)

为什么不简单:

data.table(v1 = nVector)[, index := .I][, list(unlist(strsplit(v1, " "))), by = index]
##     index V1
##  1:     1 20
##  2:     1 37
##  3:     2 38
##  4:     2 23
##  5:     3 39
##  6:     3 48
##  7:     4 45
##  8:     4 76
##  9:     5 65
## 10:     5 44
## 11:     6 86
## 12:     6 95
## 13:     6 80

或者,你可以创建一个类似下面的函数(使用函数更多是为了方便重用 - 如果只是一次性问题则不需要):

fun <- function(invec) {
  x <- strsplit(invec, " ", TRUE)
  data.table(index = rep(seq_along(x), lengths(x)), V1 = unlist(x, use.names = FALSE))
}

fun(nVector)

请注意,fixed = TRUE的使用会为您提供良好的速度提升 - 所以您应该考虑即使在&#34; data.table&#34;方法

最后,正如@Jaap建议的那样,你可以使用我的&#34; splitstackshape&#34;中的cSplit。包,像这样:

library(splitstackshape)
cSplit(data.table(v1 = nVector)[, index := .I], "v1", sep = " ", direction = "long")

更新

由于考虑到数据大小,性能是一个问题,您可能需要使用fun方法,手动创建&#34; data.table&#34;。

这是你的矢量更大版本的一些时间:

NVector <- rep(nVector, 10000)
length(NVector)
# [1] 60000

f1 <- function(invec) {
  data.table(v1 = invec)[, index := .I][
    , list(unlist(strsplit(v1, " ", TRUE))), by = index]
} 

f2 <- function(invec) {
  cSplit(data.table(v1 = invec)[, index := .I], 
         "v1", sep = " ", direction = "long")
} 

library(microbenchmark)
microbenchmark(fun(NVector), f1(NVector), f2(NVector), times = 50)
# Unit: milliseconds
#          expr       min        lq      mean    median        uq       max neval
#  fun(NVector)  13.26559  13.70738  15.89918  14.12573  15.11083  50.84675    50
#   f1(NVector) 196.95570 207.60004 223.74729 212.49649 224.78725 378.51007    50
#   f2(NVector) 167.38512 176.16370 196.28389 183.96098 202.00187 412.71760    50

更新:2017年12月28日

这些中的任何一个的表现可能至少部分取决于产生的分裂件的数量,所以我想我会:

  • 使用更多不规则数据更新答案
  • 添加更多选项,具体为:
    • 替代基础R方法
    • 使用fun
    • 替代stringi
    • 一个可能的&#34; tidyverse&#34;方法

以下是新的样本数据:

library(stringi)
set.seed(2)
NVec2 <- vapply(sample(20, 60000, TRUE), 
                function(x) paste(stri_rand_strings(x, 5, "[0-9]"), collapse = " "), 
                character(1L))

length(NVec2)
# [1] 60000

以下是新功能:

## like `fun`, but using `stri_split_fixed`
fun_stringi <- function(invec) {
  x <- stri_split_fixed(invec, " ")
  data.table(index = rep(seq_along(x), lengths(x)), V1 = unlist(x, use.names = FALSE))
}

## A base R alternative
f3 <- function(invec) stack(setNames(strsplit(invec, " ", TRUE), seq_along(invec)))

## A tidyverse approach
f4 <- function(invec) {
  data_frame(ind = seq_along(invec), 
             val = stri_split_fixed(invec, " ")) %>% 
    unnest()
} 

新的基准测试:

library(microbenchmark)
res <- microbenchmark(base = fun(NVec2), stringi = fun_stringi(NVec2),
                      data_table = f1(NVec2), splitstackshape = f2(NVec2), 
                      base_alt = f3(NVec2), tidyverse = f4(NVec2), times = 50)
res
# Unit: milliseconds
#             expr      min       lq     mean   median       uq      max neval
#             base 162.6149 174.7311 204.0177 187.3446 213.7267 443.8357    50
#          stringi 146.8655 157.6717 187.1125 168.5383 192.1952 394.1169    50
#       data_table 360.0788 382.9118 427.2276 396.0421 418.1821 598.3754    50
#  splitstackshape 542.8882 578.6317 619.9677 598.5113 626.5734 901.9400    50
#         base_alt 259.2847 293.7944 325.6021 310.7322 339.1613 492.4644    50
#        tidyverse 500.1571 519.4765 545.4757 534.1167 549.4756 713.3711    50

进一步增加数据以接近模拟实际数据集,性能真正开始趋同 - 除了&#34; splitstackshape&#34;,它可怕地放慢速度: - (

以下是一个示例:

library(stringi)
set.seed(2)
NVec3 <- vapply(sample(100:200, 125000, TRUE), 
                function(x) paste(stri_rand_strings(x, 5, "[0-9]"), collapse = " "), 
                character(1L))

system.time({out <- f2(NVec3)})
#   user  system elapsed 
#  20.89    0.03   20.94 

## Similar to your actual data
length(NVec3)
# [1] 125000
nrow(out)
# [1] 18767938

res <- microbenchmark(base = fun(NVec3), stringi = fun_stringi(NVec3),
                      data_table = f1(NVec3), base_alt = f3(NVec3), 
                      tidyverse = f4(NVec3), times = 20)
res
## Unit: seconds
##        expr      min       lq     mean   median       uq      max neval
##        base 4.967281 5.606208 5.983120 5.978414 6.345823 7.189997    20
##     stringi 4.888080 5.292926 5.811898 5.728464 6.091029 7.923210    20
##  data_table 5.625772 5.861431 6.244174 6.092079 6.420082 7.698534    20
##    base_alt 4.635496 5.015382 5.564661 5.486531 6.090838 7.034357    20
##   tidyverse 5.634781 6.186927 6.717203 6.613003 7.198013 8.154297    20

autoplot(res, log = FALSE)

enter image description here

此时,并且假设您不太可能反复这样做,任何选项都应该相当不错才能实际使用。我个人感到惊讶的是stack超越了所有其他选项......

答案 1 :(得分:0)

同意Ananda的答案很好,但是这里有一个更粗野的方式来使用stringr包和data.frames来进行未来的推断。

foo = data.frame(V1 = matrix(nVector, ncol = 1))
foo = data.frame(str_split_fixed(foo$V1, " ", 3))

bar = cbind(id = rownames(foo), foo)
bar = melt(bar, id.vars = "id")
bar = bar[order(bar$id),]
bar = bar[bar$value != "",-2]

  ## id value
  ##  1    20
  ##  1    37
  ##  2    38
  ##  2    23
  ##  3    39
  ##  3    48
  ##  4    45
  ##  4    76
  ##  5    65
  ##  5    44
  ##  6    86
  ##  6    95
  ##  6    80
相关问题