2016-03-22 30 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