2016-03-22 31 views
1

我完全超出了我对此的深度。我正在尝试使用闭包函数读取大型xml文件。唯一的问题是,我无法找到一种在闭包中创建计数器的方法,以便我可以使用计数器作为商店位置的ID。我提出了以下代码,这些代码显然存在一些(或者可能是严重的)问题。R创建一个关闭柜台

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

回答

1

这是相当多的,你只是想调用的函数来得到它去,

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

这样做是给我的错误'的错误在商店[我] < - 值:对象' I”没有找到 从调用:(函数(X,...) { new_counter < - (函数(){ I < - 0 函数(){ 我<< - i + 1的 我 } })() ns < - getNodeSet(x,path =“// event [@ type ='left link'or @ type ='entered link']”) value < - lapply(ns,xmlAttrs) store [[i]] < - value })()' – Gandalf

+0

除了上述修复之外,这是否有意义? 'store [[new_counter()]] < - value' – Gandalf

+0

现在,这给了我一个新的错误:'在商店[[new_counter()]] < - 值错误:错误参数环境分配 – Gandalf