r - 读一个数据。在 r 中间只有一行文本的文件
问题描述
我有一系列非常大的数据文件,其中包括我的数据以及以一行文本格式作为注释的附加信息。我想在表格中读取我的数据,并以某种方式将这些评论作为文本包含在一个列中,这样我就可以返回并根据评论过滤数据。此处提供了一个示例:
MTS793|BTW|ENU|1|0|.|/|:|1|0|0|A
Data Header: Time: 0.051757813 s 12/12/2019 8:15:50 AM
Data Acquisition: Timed
Station Name: ArashFatigue.cfg
Test File Name: DistorsionFatigue.tst
Time Actuator Force Actuator Displacement Top LVDT Bottom LVDT Web LVDT Flange LVDT
s lbf in in in in in
0.046875 216.01068 0.83545017 1.6925496 1.5586556 0.67528743 0.11848359
Data Header: Time: 17.038574 s 12/12/2019 8:16:11 AM
Data Acquisition: Timed
Station Name: ArashFatigue.cfg
Test File Name: DistorsionFatigue.tst
Time Actuator Force Actuator Displacement Top LVDT Bottom LVDT Web LVDT Flange LVDT
s lbf in in in in in
0.037597656 219.02016 0.83548528 1.6926224 1.5586556 0.67526972 0.11848105
0.045898438 218.44672 0.83548433 1.6925496 1.5585099 0.67528468 0.11848757
0.054199219 216.62195 0.8354823 1.6925496 1.5585828 0.675273 0.11848053
0.0625 217.15022 0.83549374 1.6926224 1.5586556 0.67527187 0.118481
0.070800781 219.7968 0.83547449 1.6925496 1.5585099 0.67526239 0.11848494
0.079101563 218.64467 0.83551377 1.6926224 1.5586556 0.67525345 0.11848123
如果没有,我想至少阅读所有评论和rbind
表格中的所有数字数据。
尝试读取 dat 时出现错误。文件,read.table
但readLines
工作正常。
解决方案
将整个数据文件读取为:
allLines <- readLines("data.dat")
从数据创建单列 data.frame:
allLines <- data.frame(a=as.character(allLines))
过滤掉不需要的文本:
allLines1 <- allLines %>%
filter(str_detect(a,"^[A-Z]"))
allLines2 <- allLines %>%
filter(str_detect(a,"^[a-z]"))
allLines3 <- rbind(allLines1,allLines2)
allLines_filter <- allLines[!(allLines$a %in% allLines3$a),]
allLines_filter <- data.frame(a=allLines_filter)
allLines_filter <- allLines_filter %>%
filter(str_detect(a,"^[0-9]"))
将数据拆分为更多列,您预计这些列会捕获被视为单元格元素的空格:
data <- str_split_fixed(allLines_filter$a , " ", 15)
将矩阵转换为数值 data.frame:
data <- as.data.frame(data, stringsAsFactors = FALSE)
data <- map_df(data, as.numeric)
将NA
单元格移动到额外的右列并删除额外的列(超过 7 列):
data[] <- t(apply(data, 1, function(x) c(x[!is.na(x)], x[is.na(x)])))
stif <- data[,1:7]
将数据的原始标头添加到数字数据的最终 data.frame
header <- c("Time", "Actuator.Force", "Actuator.Displacement",
"Top.LVDT", "Bottom.LVDT", "Web.LVDT", "Flange.LVDT")
colnames(stif) <- header
stif <- as.data.frame(sapply(stif, as.numeric))
推荐阅读
- apache - 入口 gce (GKE) 前的 Apache 反向代理
- python - 上传文件然后显示内容,django
- html - 如何链接到css中的div并制作
有固定的宽度吗?
- r - 根据使用 R 满足的条件应用标签
- dart - 在 Flutter 中 TextField 的 onChanged 回调中设置后字符串被重置
- scala - 单击 url 下载 gz 文件并使用 scala 转换为 csv
- gradle - Gradle:在从 4 迁移到 Gradle 5 时替换 task.execute()
- spring-mvc - REST api 测试和访问存储库 bean 或服务 bean
- curl - 使用 Mailchimp API 批量订阅用户
- excel - 如何使用打开的 VBA 解锁工作簿中的空白单元格