r - 如何读取 R 中的数据,其中两个标题和变量用空格分隔
问题描述
我有一个问题,因为我需要读取一些结构奇怪的数据文件,而我不知道如何读取它们。数据由两个标题组成,第一个标题从第四列开始。
每列的值都是数字,除了四行有一个用空格分隔的字符串(我无法修改数据,因为我只有数据的读取权限)。我需要读取这些值,我不在乎我是否省略了标题上的名称,或者字符串是否根据可以是四种类型的消息获得一个值。能够读取选定列的值就可以了,即使列没有名称。
这是我要读取哪种文件的示例,它们是.dat
文件:
B1 B1 B1 B1 B1 B1 B2 B2 B2 B2 B2 B2
Year Month Day Hour Min Number1 Number2 Number3 Message Number4 Message2 Number1 Number2 Number3 Message Number4 Message2
2019 4 9 8 53 3.29 46.31 0.03 There are no problems 1 There are no problems 3.00 2.00 0.00 1 There are no problems
2019 4 9 8 54 3.19 46.17 0.03 There are no problems 1 There are two problems 3.00 2.00 0.00 There are no problems 1 There are no problems
2019 4 9 8 55 3.15 46.17 0.03 There are no problems 1 3.00 3.92 0.00 There are no problems 1 There are three problems
我在这里得到了如何读取带有空格的数据文件的解决方案: How to read a character-string in a column of a data-set,但是从四列开始的两个标题表单我不知道该怎么做.. .
任何帮助将不胜感激。
解决方案
你在正确的轨道上。read_lines()
有一个名为skip
. 这使您可以跳过第一行。您会收到警告,因为列名不是唯一的,但您似乎并不太在意;-)
因此,基于您已经找到的内容(https://stackoverflow.com/a/56238232/1842673):
library(readr)
library(dplyr)
fname <- 'sample.txt'
write_file(" B1 B1 B1 B1 B1 B1 B2 B2 B2 B2 B2 B2
Year Month Day Hour Min Number1 Number2 Number3 Message Number4 Message2 Number1 Number2 Number3 Message Number4 Message2
2019 4 9 8 53 3.29 46.31 0.03 There are no problems 1 There are no problems 3.00 2.00 0.00 1 There are no problems
2019 4 9 8 54 3.19 46.17 0.03 There are no problems 1 There are two problems 3.00 2.00 0.00 There are no problems 1 There are no problems
2019 4 9 8 55 3.15 46.17 0.03 There are no problems 1 3.00 3.92 0.00 There are no problems 1 There are three problems "
,
fname
)
hdr <- read_lines(fname,n_max = 1,skip=1) #skips over the first line
cnames <- hdr %>%
trimws()%>%
strsplit('\\s+')%>%
unlist()
m <- gregexpr('\\S(?=\\s|$)',hdr,perl = T) # Find end position of columns
epos <-unlist(m)
spos <- lag(epos+1,1,default = 1)
read_fwf(fname,fwf_positions(start = spos,end = epos,col_names = cnames),skip = 1)
推荐阅读
- amazon-web-services - AWS Amplify CLI:将资源推送到云时出错
- python - 阅读 ot 使用一段不受信任的代码会有多不安全?
- kubernetes - 应用完成后清理 Kubernetes 上的 Flink 应用集群的最佳实践
- azure-devops - 在 Azure Devops 的 mono repo 中设置项目的工作目录
- pytorch-lightning - PyTorch Lightning:同一张量板图中的多个标量(例如训练和有效损失)
- c - 在 C 中努力实现 bsearch
- c++ - 使用(MLA 指令)将 C++ 转换为 ARM 程序集
- javascript - 按钮上的 Google Apps 脚本 + React Web 应用程序错误提交“不安全的 Javascript 尝试...框架正在尝试导航顶级窗口”
- java - Eclipse IDE 在项目不存在时显示警告
- python - Python乌龟中的重复功能