r - 在 R 中将字符向量列表转换为数字的最快方法

标签 r performance apply lapply

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

在我的 Intel Core i7 2.10GHz 64 位和 16GB 系统上(在 ubuntu 下):

   user  system elapsed 
  3.748   0.008   3.757 

对于真实数据集(ncol=150N~1e9),这太长了。 还有更好的选择吗?

最佳答案

这在我的系统上快了一倍:

x <- paste(myT, collapse = "\n")
library(data.table)
DT <- fread(x)
newT2 <- c(t(DT))

关于r - 在 R 中将字符向量列表转换为数字的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902971/

相关文章:

python - 使用 .apply() 定义要在 DataFrame 上使用的函数

r - 与列表中所有向量的成对比较

r - R 中的一个如何在矩阵上应用带有 "for"语句的 "if"函数来创建平滑函数

r - 应用于函数向量

c++ - 这些函数中哪个运行得更快?

r - 在ggplot中一起显示相似的条

java - 不同的屏幕尺寸

performance - 使用 ffmpeg 获取视频屏幕截图的更快方法

r - 在 R 中合并两个具有 2 列(逗号分隔内容)的数据框

r - 在具有列表列的数据帧上使用 setdiff