【发布时间】:2015-12-30 09:59:20
【问题描述】:
在R 中,将包含一组字符数字(作为字符向量)的列表转换为数字的最快方法是什么?
使用以下虚拟数据:
set.seed(2)
N = 1e7
ncol = 10
myT = formatC(matrix(runif(N), ncol = ncol)) # A matrix converted to characters
# Each row is collapsed into a single suite of characters:
myT = apply(myT, 1, function(x) paste(x, collapse=' ') )
head(myT)
制作:
[1] "0.1849 0.855 0.8272 0.5403 0.3891 0.5184 0.7776 0.5533 0.1566 0.01591"
[2] "0.7024 0.1008 0.9442 0.8582 0.3184 0.9289 0.9957 0.1311 0.2131 0.07355"
[3] "0.5733 0.5493 0.3915 0.4423 0.8522 0.6042 0.9265 0.006878 0.7052 0.71"
[... etc ...]
我可以的
library(stringi)
# In the actual dataset, the number of spaces between numbers may vary, hence "\\s+"
system.time(newT <- lapply(stri_split_regex(myT, "\\s+", omit_empty=T), as.numeric))
newT <- unlist(newT) # Final goal is to have a single vector of numbers
在我的带有 64 位和 16GB 系统的 Intel Core i7 2.10GHz 上(在 ubuntu 下):
user system elapsed
3.748 0.008 3.757
对于真实数据集(ncol=150 和 N~1e9),这太长了。
还有更好的选择吗?
【问题讨论】:
-
对你来说什么是“太长”?你几点钟了,你的系统有多快?
-
我在我的系统上添加了信息以及我得到的时间。 “太长了”意味着,如果我用真实的数据集来做,那将需要很多小时,这不是一个选择,因为它应该做很多次。因此,(并且完全独立于我得到的时间),我只是在寻找实现这一目标的最快方法,以便看看我是否能做到。
-
我想知道你是怎么得到
myT的。也许您需要更改之前的步骤。 -
随意发布答案。请注意,
fread接受一个将文件预处理为输入的 shell 命令。
标签: r performance apply lapply