【问题标题】:capture text output as structured data frame [closed]将文本输出捕获为结构化数据框[关闭]
【发布时间】:2016-03-04 14:02:42
【问题描述】:

我以以下形式将输出作为文本流式传输:

[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 捕获它,但我不太确定如何将其转换为数据框。

【问题讨论】:

  • “流式传输”是什么意思?
  • 该函数连接到金融网站并在发生时返回信息。无论如何我都会在 5 秒内关闭连接
  • 我们很难重现您的程序。您正在谈论“功能”等的“输出流”。这使我们很难考虑如何帮助您。我们甚至不知道您捕获的输出是什么类型的对象。请阅读stackoverflow.com/questions/5963269/…
  • 你是对的。让我们忘记流媒体部分。假设我已经在长度为 n 的字符向量中捕获了我需要的输出,其值都与上面报告的形式相同...如何将其转换为数据帧?

标签: regex r capture read.table


【解决方案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)))

输出可能更漂亮,但我相信您可以稍微清理一下。如果您的所有数据都遵循相同的模式(即用空格分隔并且您不希望等号之前的位),它就可以工作。

【讨论】:

  • 谢谢丹。这工作得很好:)
  • 没有问题,如果是最好的答案,你要接受吗?
【解决方案2】:

另一种可能的解决方案,

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

数据

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 ")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2023-03-16
    • 2010-09-05
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多