fab*_*iog 5 string bash r fix-protocol tidyr
我有一个 35=S(报价消息;“标签=值”)的 csv/日志文件,我需要将费率提取到适当的 CSV 文件中以进行数据挖掘。这不是严格的 FIX 相关,它更多是关于如何清理数据集的 R 相关问题。
原始消息如下所示:
190=1.1204 ,191=-0.000029,193=20141008,537=0 ,631=1.12029575,642=0.000145,10=56
190=7.20425,191=0.000141 ,537=0 ,631=7.2034485,10=140 , ,
190=1.26237,191=0 ,537=1 ,10=068 , , ,
Run Code Online (Sandbox Code Playgroud)
我首先需要获得一个看起来像这样的中间数据集,其中对齐了相同的标签。
190=1.1204 ,191=-0.000029,193=20141008,537=0,631=1.12029575,642=0.000145,10=56
190=7.20425,191=0.000141 , ,537=0,631=7.2034485 , ,10=140
190=1.26237,191=0 , ,537=1, , ,10=068
Run Code Online (Sandbox Code Playgroud)
反过来,这将需要转换为:
190 ,191 ,193 ,537,631 ,642 ,10
1.1204 ,-0.000029,20141008,0 ,1.12029575,0.000145,56
7.20425,0.000141 , ,0 ,7.2034485 , ,140
1.26237,0 , ,1 , , ,068
Run Code Online (Sandbox Code Playgroud)
我正在用 awk 开发一个 bash 脚本,但我想知道我是否可以在 R 中做到这一点。目前,我最大的挑战是到达中间表。从中间到决赛桌,我想到将 R 与 tidyr 包一起使用,特别是函数“separate”。如果有人可以提出更好的逻辑,我将不胜感激!
另一种可能性。以与 @Andrie 相同的开头scan,但也使用参数strip.white和na.strings:
x <- scan(text = "190=1.1204 ,191=-0.000029,193=20141008,537=0 ,631=1.12029575,642=0.000145,10=56
190=7.20425,191=0.000141 ,537=0 ,631=7.2034485,10=140 , ,
190=1.26237,191=0 ,537=1 ,10=068 , , ,",
sep = ",",
what = "character",
strip.white = TRUE,
na.strings = "")
# remove NA
x <- x[!is.na(x)]
Run Code Online (Sandbox Code Playgroud)
然后使用colsplitand dcastfromreshape2包:
library(reshape2)
# split 'x' into two columns
d1 <- colsplit(string = x, pattern = "=", names = c("x", "y"))
# create an id variable, needed in dcast
d1$id <- ave(d1$x, d1$x, FUN = seq_along)
# reshape from long to wide
d2 <- dcast(data = d1, id ~ x, value.var = "y")
# id 10 190 191 193 537 631 642
# 1 1 56 1.12040 -0.000029 20141008 0 1.120296 0.000145
# 2 2 140 7.20425 0.000141 NA 0 7.203449 NA
# 3 3 68 1.26237 0.000000 NA 1 NA NA
Run Code Online (Sandbox Code Playgroud)
因为你提到tidyr:
library(tidyr)
d1 <- separate(data = data.frame(x), col = x, into = c("x", "y"), sep = "=")
d1$id <- ave(d1$x, d1$x, FUN = seq_along)
spread(data = d1, key = x, value = y)
# id 10 190 191 193 537 631 642
# 1 1 56 1.1204 -0.000029 20141008 0 1.12029575 0.000145
# 2 2 140 7.20425 0.000141 <NA> 0 7.2034485 <NA>
# 3 3 068 1.26237 0 <NA> 1 <NA> <NA>
Run Code Online (Sandbox Code Playgroud)
这会将值保留为character。如果你愿意的话numeric,可以设置convert = TRUE进去spread。