r - 从文本文件中读取特定列:R
问题描述
我正在尝试读取文本文件并创建一些特定列(大约 12 个)(位于特定长度)的数据框(称为数据集),如下所示:
x <- fread("file1.txt",colClasses = "character", sep = "\n", header = FALSE, verbose = FALSE,strip.white = FALSE)
y <- fread("file2.txt",colClasses = "character", sep = "\n", header = FALSE, verbose = FALSE,strip.white = FALSE)
# combine them
x = rbind(x,y)
# We basically read the whole file as a string and then read substrings
# corresponding to each variable start and finish lengths.
Var1= sapply(as.list(x$V1), stri_sub, from = 80, to = 82)
Var1= as.data.frame(Var1)
Var2= sapply(as.list(x$V1), stri_sub, 83, 89)
Var2= as.data.frame(Var2)
dataset = cbind(Var1,Var2)
运行两个分别有 200K 和 300K 行的文本文件大约需要 1 分钟。它们每行有 1800 个字符。有没有更快的方法来运行它?我将阅读大约 200 个这样的文件。
解决方案
我认为您可以通过以下方式简化代码
x <- Reduce(rbind, lapply(1:2, function(k) fread(paste0("file",k,".txt"),
colClasses = "character",
sep = "\n",
header = FALSE,
verbose = FALSE,
strip.white = FALSE)))
dataset <- data.frame(Var1= substr(x$V1, 80, 82), Var2 = substr(x$V1,83,89))
当您substr
在整个列上使用时,第二行可能会节省更多时间。
推荐阅读
- python - 如何解决我在编写 while 循环时遇到的“关键错误:t”?
- spring-boot - Spring Cloud Stream:Kafka生产者和消费者的多个绑定器具有单独的jaas配置不能一起工作
- python - 多值请求解析即将用于选择多个
- bash - 如何将除前两个之外的所有 bash 参数设置为 git 别名
- c++ - C++ 错误:调用非 constexpr 函数
- sql - 尝试在一个查询中使用两个联接时重复计数
- html - Bootstrap 垂直导航无法按预期工作
- java - 有没有更好的方法在 Java 中使用通配符?
- python - 如何将熊猫数据框插入包含列表的列的表中
- http - 使用 net/http 构建子路由器的好方法