将我的评论转换为答案,这是一种使用“data.table”包的方法。
library(data.table)
x <- "path/to/yourLogFile.txt"
mydt <- fread(x, header = FALSE, col.names = c("Key", "Time"))
dcast(mydt[, Time := as.numeric(sub("Time=", "", Time))][
, Ind := sequence(.N), Key], Key ~ Ind, value.var = "Time")[
, Diff := `2` - `1`][]
# Key 1 2 Diff
# 1: Key=1 146656456446 146656456448 2
# 2: Key=2 146656456447 146656456450 3
使用我的“splitstackshape”包的另一种类似方法以及读取数据的相同步骤可能如下所示:
library(splitstackshape)
dcast(getanID(cSplit(mydt, "Time", "="), "Key"),
Key ~ Time_1 + .id, value.var = "Time_2")[
, Diff := Time_2 - Time_1, by = Key][]
# Key Time_1 Time_2 Diff
# 1: Key=1 146656456446 146656456448 2
# 2: Key=2 146656456447 146656456450 3
为了读取日志文件,我做了以下假设:
- 您知道应该有两列。
- 您的日志文件目前没有列名(因此是
header = FALSE)。
- 您希望数据由
| 字符分隔,fread 将能够自动检测到。
更新
它并不漂亮,但它确实有效....
dcast(getanID(cSplit(mydt, names(mydt), "="), "Key_2"),
Key_2 ~ .id, fun=list(I, I), value.var = list("Field_2", "Time_2"), fill = 0)[
, c("Field_2_I_1", "Diff") := list(NULL, Time_2_I_2 - Time_2_I_1)][]
## Key_2 Field_2_I_2 Time_2_I_1 Time_2_I_2 Diff
## 1: 1 10 146656456446 146656456448 2
## 2: 2 11 146656456447 146656456450 3
样本数据
## Just to simulate a log file like the one you describe....
## "temp" would be your actual file....
x <- c("Key=1|Time=146656456446", "Key=2|Time=146656456447",
"Key=1|Time=146656456448|field=10", "Key=2|Time=146656456450|field=11")
temp <- tempfile()
writeLines(x, temp)
mydt <- fread(temp, header = FALSE, fill = TRUE,
col.names = c("Key", "Time", "Field"))
mydt
## Key Time Field
## 1: Key=1 Time=146656456446
## 2: Key=2 Time=146656456447
## 3: Key=1 Time=146656456448 field=10
## 4: Key=2 Time=146656456450 field=11