2016-03-04 42 views
-4

我有輸出流作爲文本在以下形式:捕獲文本輸出作爲結構化數據幀

[2] "TWS OrderStatus: orderId=12048 status=PreSubmitted 
         filled=0 remaining=300 averageFillPrice=0 " 

[3] "TWS OrderStatus: orderId=12049 status=PreSubmitted 
         filled=0 remaining=300 averageFillPrice=0 " 

我想捕捉這樣的輸出,並將它與列轉換爲一個數據幀:orderId, status, filled, remaining, averageFillPrice

我想知道什麼是最有效的方式來做到這一點。

我試圖用capture.output捕獲它,但後來我不確定如何將它轉換爲數據幀。

+0

你的意思是 「流」? – nrussell

+0

該功能連接到財務網站,並在發生時返回信息。不管怎樣,我在5秒內關閉連接 – kalka

+0

我們很難重現您的程序。你正在通過「功能」來討論「輸出流」,這使我們很難考慮如何幫助你。我們甚至不知道您捕獲的輸出是什麼類型的對象。請閱讀http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – coffeinjunky

回答

1

我想你可以用一些基本字符串函數來做到這一點。如果你已經存儲在列表中的字符串,如下面的例子,你可以創建一個函數來提取所需的信息,然後把它應用到列表和輸出的數據幀:

a <- "TWS OrderStatus: orderId=12048 status=PreSubmitted filled=0 remaining=300 averageFillPrice=0 " 
b <- "TWS OrderStatus: orderId=12049 status=PreSubmitted filled=0 remaining=300 averageFillPrice=0 " 
dat <- list(a, b) 

extract <- function(x) { 
    a <- as.vector(strsplit(x, " ")[[1]])[-(1:2)] 
    return(sapply(a, function(b) substr(b, gregexpr("=", b)[[1]] + 1, nchar(b)))) 
} 

as.data.frame(t(sapply(dat, extract))) 

輸出可以比較漂亮,但我相信你可以把它清理一下。如果您的所有數據遵循相同的模式(即按空格拆分,並且您不想在等號之前的位),那麼它就可以工作。

+0

謝謝丹。這工作完美:) – kalka

+0

沒有probs,你想接受答案,如果它是最好的? –

0

另一種可能的解決方案,

library("splitstackshape") 
library("stringr") 
makedf <- function(x) { 
v1 <- str_split(trimws(sub(".*?:(.+)", "\\1", x)), " ") 
v3 <- as.data.frame(sapply(v1, function(i) t(i))) 
v4 <- as.data.frame(t(cSplit(v3, "V1", "="))) 
v4[] <- lapply(v4, as.character) 
colnames(v4) <- v4[1,] 
v4 <- v4[-1,] 
    } 
FinalDF <- rbindlist(lapply(txt, makedf)) 
FinalDF 
# orderId  status filled remaining averageFillPrice 
#1: 12048 PreSubmitted  0  300    0 
#2: 12049 PreSubmitted  0  300    0 

DATA

txt <- list("TWS OrderStatus: orderId=12048 status=PreSubmitted filled=0 remaining=300 averageFillPrice=0 ", 
    "TWS OrderStatus: orderId=12049 status=PreSubmitted filled=0 remaining=300 averageFillPrice=0 ")