将列表的控制台输出转换为真正的 R 列表

2024-01-10

有人刚刚发布了一些控制台输出作为示例。 (这种情况经常发生,我有将打印输出转换为向量和数据帧的策略。)我想知道是否有人有一种优雅的方法将其解析为真正的 R 列表?

test <- "[[1]]
[1] 1.0000 1.9643 4.5957

[[2]]
[1] 1.0000 2.2753 3.8589

[[3]]
[1] 1.0000 2.9781 4.5651

[[4]]
[1] 1.0000 2.9320 3.5519

[[5]]
[1] 1.0000 3.5772 2.8560

[[6]]
[1] 1.0000 4.0150 3.1937

[[7]]
[1] 1.0000 3.3814 3.4291"

这是一个包含命名和未命名节点的示例:

 L <- 
structure(list(a = structure(list(d = 1:2, j = 5:6, o = structure(list(
    w = 2, 4), .Names = c("w", ""))), .Names = c("d", "j", "o"
)), b = "c", c = 3:4), .Names = c("a", "b", "c"))

> L
$a
$a$d
[1] 1 2

$a$j
[1] 5 6

$a$o
$a$o$w
[1] 2

$a$o[[2]]
[1] 4



$b
[1] "c"

$c
[1] 3 4

我已经完成了如何的代码str处理列表,但它本质上是进行逆变换。我认为这需要在某种程度上按照这些思路进行构建,其中将递归调用类似这样的逻辑,因为列表可以命名(其中最后一个索引之前有“$”)或未命名(在这种情况下)将有一个数字括在“[[.]]”中。

parseTxt <- function(Lobj) {
   #setup logic
#  Untested code... basically a structure to be filled in
 rdLn <- function(Ln) {
     for( ln in length(inp) ) {
         m <- gregexpr("\\[\\[|\\$", "$a$o[[2]]")
         separators <- regmatches("$a$o[[2]]", m)
         curr.nm=NA
        if ( tail( separators, 1 ) == "$" ){ 
                   nm <- sub("^.+\\$","",ln)
                   if( !nm %in% curr.nm){ curr.nm <-c(nm, curr.nm) }
        } else { if (tail( separators, 1 ) == '[[' ){
            # here need to handle "[[n]]" case
        } else {  and here handle the "[n]" case
                    }
     }
 }

这是我的解决方案。它在您的测试用例以及我测试过的其他几个测试用例上都运行良好。

deprint <- function(ll) {
    ## Pattern to match strings beginning with _at least_ one $x or [[x]]
    branchPat <- "^(\\$[^$[]*|\\[\\[[[:digit:]]*\\]\\])"
    ## Pattern to match strings with _just_ one $x or one [[x]]
    trunkPat <- "^(\\$[^$[]*|\\[\\[[[:digit:]]*\\]\\])\\s*$"
    ##
    isBranch <- function(X) {
        grepl(branchPat, X[1])
    }
    ## Parse character vectors of lines like "[1] 1 3 4" or
    ## "[1] TRUE FALSE" or c("[1] a b c d", "[5] e f") 
    readTip <- function(X) {
        X <- paste(sub("^\\s*\\[.*\\]", "", X), collapse=" ")
        tokens <- scan(textConnection(X), what=character(), quiet=TRUE)
        read.table(text = tokens, stringsAsFactors=FALSE)[[1]]
    }

    ## (0) Split into vector of lines (if needed) and
    ##     strip out empty lines
    ll <- readLines(textConnection(ll))
    ll <- ll[ll!=""]

    ## (1) Split into branches ...
    trunks <- grep(trunkPat, ll)
    grp <- cumsum(seq_along(ll) %in% trunks)
    XX <- split(ll, grp)
    ## ... preserving element names, where present
    nms <- sapply(XX, function(X) gsub("\\[.*|\\$", "", X[[1]]))
    XX <-  lapply(XX, function(X) X[-1])
    names(XX) <- nms

    ## (2) Strip away top-level list identifiers.
    ## pat2 <- "^\\$[^$\\[]*"
    XX <- lapply(XX, function(X) sub(branchPat, "", X))

    ## (3) Step through list elements:
    ## - Branches will need further recursive processing.
    ## - Tips are ready to parse into base type vectors.
    lapply(XX, function(X) {
        if(isBranch(X)) deprint(X) else readTip(X)
    })
}

With L,您的更复杂的示例列表,它给出的内容如下:

## Because deprint() interprets numbers without a decimal part as integers,
## I've modified L slightly, changing "list(w=2,4)" to "list(w=2L,4L)" 
## to allow a meaningful test using identical(). 
L <-
structure(list(a = structure(list(d = 1:2, j = 5:6, o = structure(list(
    w = 2L, 4L), .Names = c("w", ""))), .Names = c("d", "j", "o"
)), b = "c", c = 3:4), .Names = c("a", "b", "c"))

## Capture the print representation of L, and then feed it to deprint()
test2 <- capture.output(L)
LL <- deprint(test2)
identical(L, LL)
## [1] TRUE
LL
## $a
## $a$d
## [1] 1 2
## 
## $a$j
## [1] 5 6
## 
## $a$o
## $a$o$w
## [1] 2
## 
## $a$o[[2]]
## [1] 4
## 
## $b
## [1] "c"
## 
## $c
## [1] 3 4

这是它处理打印表示的方式test,您更常规的列表:

deprint(test)
## [[1]]
## [1] 1.0000 1.9643 4.5957
## 
## [[2]]
## [1] 1.0000 2.2753 3.8589
## 
## [[3]]
## [1] 1.0000 2.9781 4.5651
## 
## [[4]]
## [1] 1.0000 2.9320 3.5519
## 
## [[5]]
## [1] 1.0000 3.5772 2.8560
## 
## [[6]]
## [1] 1.0000 4.0150 3.1937
## 
## [[7]]
## [1] 1.0000 3.3814 3.4291

再举一个例子:

head(as.data.frame(deprint(capture.output(as.list(mtcars)))))
#    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将列表的控制台输出转换为真正的 R 列表 的相关文章

随机推荐

  • SharePoint 站点定义

    我基于发布门户创建了一个简单的站点定义 每次我想使用模板创建网站集时 都会收到以下错误消息 您选择的模板无效或无法找到 我不使用任何自定义功能 仅使用发布门户 site def 的默认功能 有什么提示吗 有一个错误日志 但它只提供了上面的信
  • 在 R 中使用 Quantmod 进行下载-保存-加载往返

    我想使用 quantmod 下载数据 将它们保存到文件中以便稍后加载 下面一段R代码 library quantmod symbols lt c DEXUSUK STLFSI GDP tmpdir lt tempdir getSymbols
  • 这些 RubyInstaller 2.4 组件有什么作用?

    几天之前 Windows 版 RubyInstaller 2 4 发布 https rubyinstaller org 2017 05 25 rubyinstaller 2 4 1 1 released html 安装后 它会问我以下问题
  • Neo4j over Bolt 协议具有非常高的延迟

    我正在将 Neo4j 用于一个项目 使用此处找到的 NET 官方 Neo4j 驱动程序 https www nuget org packages Neo4j Driver https www nuget org packages Neo4j
  • array.contains 的 jquery 版本

    jQuery 可以测试数组中是否存在对象 作为核心功能的一部分或通过可用的插件 另外 我正在寻找类似的东西array remove 这将从数组中删除给定的对象 jQuery 可以帮我处理这个问题吗 jQuery inArray http d
  • 进程已完成,退出代码 -1073741515 (0xC0000135)

    我正在运行一个 python 脚本 它曾经可以工作 现在甚至在我的另一台笔记本电脑上也可以 但不能在我当前的计算机上 我只是得到错误代码 Process finished with exit code 1073741515 0xC00001
  • 如何使用内联函数声明字典

    在将函数用作字典的元素之前 是否必须正式定义该函数 def my func print my func d function my func 我宁愿内联定义该函数 我只是想输入我想要做的事情 但是 python 语法的空白策略使得在字典中定
  • Web 应用程序的容器管理安全性

    我对容器管理的安全性完全陌生 需要一些帮助来在我的 Web 应用程序中配置它 我想限制对我的 Web 应用程序中的 jsp 的访问 这就是我在 web xml 中配置安全性的方式
  • Hbase 和 BigTable 有什么区别?

    谁能告诉我 Apache HBase 数据库和 Bigtable 之间有什么区别 或者它们是相同的吗 如果有的话 哪一个支持关系 如果他们是大搜索者 有什么区别 它们很相似 但又不一样 Bigtable 最初于 2005 年发布 但并未发布
  • RStudio 全局设置(选项)导出/导入

    我想导出 导入 RStudio 全局选项 通常可以在 RStudio 的 工具 gt 全局选项 中找到并设置这些选项 理想情况下 我可以运行一行代码 将现有设置保存到文件中 然后运行另一行代码以从此文件加载这些设置 这些选项包括 GUI 的
  • Git rebase 失败,“您对以下文件的本地更改将被合并覆盖”。没有本地改变吗?

    这是我尝试将 bugfix 分支合并到 master 分支以准备将其推向上游的记录 自从创建 bugfix 分支以来 已经有一些上游更改被拉入 master 并且现在拒绝 rebase 它引发错误的文件在打开时没有差异 没有添加 删除或重命
  • tomcat 重新启动 => 找不到 SessionFactory [uuid=...,name=null]

    继续解决这个情况 https stackoverflow com questions 6506476 java lang illegalstateexception unread block data 我已经更新了hibernate ond
  • 如何在 C# 中将 XMLSerialize 用于 Enum 类型属性?

    我有一个简单的枚举 enum simple one two three 我还有一个具有 type 属性的类simple 我尝试用以下属性装饰它 XmlAttribute DataType int 但是 当我尝试使用序列化它时 它失败了Xml
  • 错误:连接失败(没有到主机的路由)

    上下文 我有一个 Xamarin Android 应用程序 它连接到 WebAPI 以获取不同的信息 问题 尝试访问服务器时出现以下错误 System Net Http HttpRequestException 发送请求时发生错误 gt S
  • 当文本字段为空时,如何在 Xcode UI 测试中测试 UITextField?

    我正在做一个UITest在 Xcode 中 当我记录测试时 它工作正常 但当我运行测试时 它会出现错误 这些是发生错误的代码行 XCUIElement clearTextTextField app textFields containing
  • 在本地 html 文件中使用 JavaScript 设置 Cookie

    我有以下目录树 folder1 folder2 page1 html page2 html 如果我设置一些cookiepage1 html使用 JavaScript 该 cookie 使用的路径是什么 Edit 让我更好地解释一下 我正在处
  • 最佳匹配:错误警告,但输出看起来不错

    我通过 MatchIt 和 optmatch 包执行了最佳匹配 library MatchIt library optmatch data lalonde optimal lt matchit treat age educ black da
  • ionic 2 错误 cordova 不可用

    我正在尝试在新的 ionic 2 项目 最新的 ionic2 版本 中使用 cordova GooglePlus 插件 但我总是遇到有关 cordova 的错误 该插件已正确安装并显示在插件文件夹中 我尝试过的一种方法是 import Go
  • jQuery Fancybox 无法识别元素

    a href https xenogamers org attachment php attachmentid 3655 d 1350682390 img class thumbnail border 0 alt Click image f
  • 将列表的控制台输出转换为真正的 R 列表

    有人刚刚发布了一些控制台输出作为示例 这种情况经常发生 我有将打印输出转换为向量和数据帧的策略 我想知道是否有人有一种优雅的方法将其解析为真正的 R 列表 test lt 1 1 1 0000 1 9643 4 5957 2 1 1 000