R 创建一个关闭计数器
R Create a closure counter
我对此完全不知所措。我正在尝试使用闭包函数读取大型 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。
差不多就是这样,您只需调用该函数即可,
new_counter <- (function() {
i <- 0
function() {
i <<- i + 1
i
}
})()
我对此完全不知所措。我正在尝试使用闭包函数读取大型 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。
差不多就是这样,您只需调用该函数即可,
new_counter <- (function() {
i <- 0
function() {
i <<- i + 1
i
}
})()