r - 在R中解析txt文件
问题描述
我需要像这样解析一个txt文件:
2021 Sep 27 15:54:50 avg_dur = 0.321 s
2021 Sep 27 15:54:52 avg_dur = 0.036 s
2021 Sep 27 15:54:54 avg_dur = 0.350 s
2021 Sep 27 15:54:56 avg_dur = 0.317 s
我有兴趣解析 R 数据框中的日期和数字。我正在尝试这样的解析器(仅适用于日期):
df <- read_table("myFile.txt", col_names = FALSE, col_types = cols(X1 = col_datetime(format = "%Y %b %d %H:%M:%S")))
但它不起作用:
Warning: 31502 parsing failures.
row col expected actual file
1 X1 date like %Y %b %d %H:%M:%S 2021 'uclStats/91.211.159.43-dash_d1_gwv_vos-u5.log-avg'
2 X1 date like %Y %b %d %H:%M:%S 2021 'uclStats/91.211.159.43-dash_d1_gwv_vos-u5.log-avg'
3 X1 date like %Y %b %d %H:%M:%S 2021 'uclStats/91.211.159.43-dash_d1_gwv_vos-u5.log-avg'
4 X1 date like %Y %b %d %H:%M:%S 2021 'uclStats/91.211.159.43-dash_d1_gwv_vos-u5.log-avg'
5 X1 date like %Y %b %d %H:%M:%S 2021 'uclStats/91.211.159.43-dash_d1_gwv_vos-u5.log-avg'
... ... ........................... ...... ...................................................
See problems(...) for more details.
问题显然是它试图用整个日期时间的配方解析第一列。
在数据框中解析此 txt 文件的正确方法是什么?
问候,S。
解决方案
1) read.zoo将其读入动物园对象,z
然后将其转换为数据框(或将其保留为动物园对象)。这利用了在转换为 POSIXct 时将忽略索引列末尾的垃圾这一事实。
我们Lines
在最后的注释中使用了可重复性,但text = Lines
可以替换为"myFile.txt"
.
library(zoo)
z <- read.zoo(text = Lines, sep = "=",
format = "%Y %b %d %H:%M:%S", tz = "", comment.char = "s")
fortify.zoo(z)
给出这个具有 POSIXct 和数字列的数据框:
Index z
1 2021-09-27 15:54:50 0.321
2 2021-09-27 15:54:52 0.036
3 2021-09-27 15:54:54 0.350
4 2021-09-27 15:54:56 0.317
2) Base R 将其读入数据框dd
,然后将第一列转换为POSIXct。
dd <- read.table(text = Lines, sep = "=", comment.char = "s")
dd$V1 <- as.POSIXct(dd$V1, format = "%Y %b %d %H:%M:%S")
笔记
Lines <- "2021 Sep 27 15:54:50 avg_dur = 0.321 s
2021 Sep 27 15:54:52 avg_dur = 0.036 s
2021 Sep 27 15:54:54 avg_dur = 0.350 s
2021 Sep 27 15:54:56 avg_dur = 0.317 s"
推荐阅读
- c# - EF Core Power Tools 逆向工程师在不同 SQL 服务器上的模型上创建不同的属性
- javascript - Material UI React - 找不到模块:无法解析“@material-ui/pickers”
- r - 在 ggpmisc 中使用 stat_fit_glance() 时忽略未知参数:label.x.npc、label.y.npc
- javascript - ReactJS useState 不更新 momentJS 道具
- javascript - Json文件在长度上苦苦挣扎
- podman - 如何使用无根 podman 创建持久卷?
- load-balancing - 如何将 websocket 流量从 GCP 负载均衡器传送到 websocket 服务器
- c# - 如何使用 Linq 检查对象列表属性是否允许来自另一个列表的值
- javascript - 归还包含特定类型的书籍
- c - 帧数据如何存储在 libav 中?