【问题标题】:R Create a closure counterR 创建一个关闭计数器
【发布时间】:2016-07-08 20:29:12
【问题描述】:

我对此完全不了解。我正在尝试使用闭包函数读取一个大型 xml 文件。唯一的问题是,我无法找到一种在关闭中创建柜台的方法,以便我可以将柜台用作商店位置的 id。我想出了以下代码,它显然存在一些(或可能是严重的)问题。

branchFunction <- function() {
  store <- new.env() 
  func <- function(x, ...) {
    new_counter <- function() {
      i <- 0
      function() {
        i <<- i + 1
        i
      }
    }
    ns <- getNodeSet(x,path = "//event[@type='left link' or @type='entered link']")
    value <- lapply(ns, xmlAttrs)
    store[[i]] <- value
  }
  getStore <- function() { as.list( store ) }
  list(event = func, getStore=getStore)
}

myfunctions <- branchFunction()

xmlEventParse(file = "xml.xml", handlers = NULL, branches = myfunctions)

#to see what is inside
l <- myfunctions$getStore()

这里是示例data

【问题讨论】:

    标签: r xml-parsing closures sax


    【解决方案1】:

    差不多就是这样,你只是想调用函数来启动它,

    new_counter <- (function() {
      i <- 0
      function() { 
        i <<- i + 1
        i
      }
    })()
    

    【讨论】:

    • 这样做会给我错误Error in store[[i]] &lt;- value : object 'i' not found Called from: (function (x, ...) { new_counter &lt;- (function() { i &lt;- 0 function() { i &lt;&lt;- i + 1 i } })() ns &lt;- getNodeSet(x, path = "//event[@type='left link' or @type='entered link']") value &lt;- lapply(ns, xmlAttrs) store[[i]] &lt;- value })(&lt;pointer: 0x0000000016af3f40&gt;)
    • 连同您的上述修复,这是否有意义? store[[new_counter()]] &lt;- value
    • 现在,这给了我一个新错误:Error in store[[new_counter()]] &lt;- value : wrong args for environment subassignment
    • 呃……谢谢。只是想让您知道,如果将计数器放在函数func 中,它会继续重复值 1。如果它高于func 并低于branchfunction,则它可以正常工作,如下所示:branchFunction &lt;- function() { store &lt;- new.env() new_counter &lt;- (function() { i &lt;- 0 function() { i &lt;&lt;- i + 1 i } })() func &lt;- function(x, ...) { ns &lt;- getNodeSet(x,path = "//event[@type='left link' or @type='entered link']") value &lt;- lapply(ns, xmlAttrs) store[[toString(new_counter())]] &lt;- value } ## rest is same
    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2022-12-07
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多