数字向量和数据表索引

8

如何将以下向量与每个数字的索引一起放入 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万个值。

@Nancy,我想提一下,解释预分配列表的内容。 - mrp
Ananda的data.table解决方案非常好,但是仅供参考,我想指出的是,无论您是否使用data.table,都不需要循环执行此类任务。例如,要创建索引向量,可以执行idx = rep(1:length(nVector), sapply(strsplit(nVector, split=" "), length))。这利用了R中许多函数矢量化的事实,这意味着它们在单个函数调用中对向量的每个元素进行操作。 - eipi10
1
@eipi10,...并且为了改进你的建议,使用lengths代替sapply(..., length)快得多.... - A5C1D2H2I1M1N2O1R2T1
谢谢@AnandaMahto。很高兴了解到lengths - eipi10
@eipi10,你的方法是最快的... - A5C1D2H2I1M1N2O1R2T1
1
啊,但是你的方法在代码高尔夫比赛中仍然会获胜。 - eipi10
2个回答

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将为您提供很好的速度提升-因此即使在“data.table”方法中,您也应该考虑这一点。
最后,正如@Jaap所建议的那样,您可以使用我的“splitstackshape”包中的cSplit,像这样:
library(splitstackshape)
cSplit(data.table(v1 = nVector)[, index := .I], "v1", sep = " ", direction = "long")

更新

由于数据规模较大,性能是一个问题,您可能希望使用手动创建"data.table"的fun方法。

这是一些更大版本向量的时间计算:

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方法
    • 使用stringi替代fun的方法
    • 可能的“整洁数据”方法

以下是新的样本数据:

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

如果继续增加数据以更接近模拟实际数据集,性能会开始收敛--除了"splitstackshape",它的效率会变得非常慢 :-(

以下是一个示例:

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比其他选项表现更好....


使用以下代码进行数据处理:library(splitstackshape); dt <- cSplit(data.table(v1 = nVector)[, index := .I], "v1", sep = " ", direction = "long") ;-) - Jaap

0

虽然Ananda的答案很好,但这里有一种更加粗暴的方法,使用stringr包和数据框进行未来推断。

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

冒昧说一句,有时候我们不能忽视提问者发布了一个合理的方法,但期望更高效的代码来解决更大的问题。例如,在您此处的回答中,您遇到了一个问题,即在stri_split_fixed中硬编码要使用的拆分数。当他们指出其平均项长度在160个项目范围内时,这可能不是一个好主意;-)无论如何,请继续花时间在SO上。我们可以直言不讳,但也可以在彼此了解后非常友好... - A5C1D2H2I1M1N2O1R2T1
@Ananda 一点也不失礼。我在这里学习,并感谢您的反馈! - Nancy
我也倾向于从用户的角度来看待这类问题,如果我遇到了答案,我会考虑自己需要什么。有时,“最好”的答案很难理解,这时用一种不同的方式来看待它可能会有所帮助......也许是通过更有经验的方法。这个答案可能不值得被接受,但并不一定是无用的。 - Nancy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接