r - 从 .txt 文件中提取一些数据
问题描述
经过一个漫长的早晨,我放弃了!
我有以下文本文件: StationLog.txt
包含以下内容:
Version = 2.0
StationName = STN67_P70
BeginTime = 2017-10-06.03:25:00
EndTime = 2017-10-06.03:55:00
IgnoreNo = 5000
PumpedVolume = 0
我需要提取 BeginTime、EndTime 和 StationName,这些标题很好,作为输入另一段代码的值。
这个想法是我不必手动执行,因为及时会有很多这些文件。
到目前为止,我必须遵循各种其他指南:
a <- read.fwf("StationLog.txt", c(37,100), stringsAsFactors=FALSE)
a <- a[grep("=", a$V1), ]
a <- cbind(
do.call( rbind, strsplit(a$V1, "=\\s+") )
但是碰壁了,任何帮助将不胜感激!
解决方案
基于read.table
函数,您可以使用参数来做您想做的事情。
如果每行只有一个=
,并且 BeginTime、EndTime 和 StationName 在所有文件中具有相同的写法,则以下建议将起作用:
read.table(
file ="StationLog.txt",
header =FALSE, # No column names
sep ="=", # separator character
strip.white =TRUE, # remove multiple white character
row.names =1, # the first column contains the rownames
stringsAsFactors=FALSE
)[c("BeginTime", "EndTime", "StationName"), # extract the 3 infos based on their names corresponding to the rownames
,drop=FALSE] # keep the data.frame format
结果:
V2
BeginTime 2017-10-06.03:25:00
EndTime 2017-10-06.03:55:00
StationName STN67_P70
推荐阅读
- php - Codeigniter 输入到有条件的数据库
- c - 没有crontab,我如何每天发送信号?
- excel - excel翻译函数为公式
- php - 如何将多个查询的结果存储在变量中并使用 php.ini 访问它。(程序风格)
- reactjs - 在 Next.js 中使用 Google ReCaptcha v3
- rust - 0usize 代表什么,为什么它没有在原语中列出?
- kotlin - kotlin 中计算器的一元和二元减号运算符
- java - 我无法让 CompletableFuture supplyAsync 方法返回任何东西
- node.js - 如何使用 axios 在另一个网站上填写和提交表单?
- c++ - 默认移动语义与复制相同吗?