从R中的对象列表中删除元素的最佳方法是什么
在玩R中的引用类时,我遇到了一些感觉不太好的东西。如果我有一个对象列表,有没有一种方法可以从列表中删除一个单独的项目,而不需要查找其索引?在下面的(工作)示例中,我希望有一种更好的方法来实现removeContent(),即从列表中删除项而不必循环。如果可能的话,我会尽量坚持到底从R中的对象列表中删除元素的最佳方法是什么,r,reference-class,R,Reference Class,在玩R中的引用类时,我遇到了一些感觉不太好的东西。如果我有一个对象列表,有没有一种方法可以从列表中删除一个单独的项目,而不需要查找其索引?在下面的(工作)示例中,我希望有一种更好的方法来实现removeContent(),即从列表中删除项而不必循环。如果可能的话,我会尽量坚持到底 Element <- setRefClass( Class ="Element", fields = list( m_name = "character", contentList = "
Element <- setRefClass(
Class ="Element",
fields = list(
m_name = "character",
contentList = "list"
),
methods = list(
initialize = function(name = NULL) {
"Element constructor, @param name, The name of the tag (optional)"
if(!is.null(name)) {
m_name <<- name
}
},
addContent = function(content) {
"Appends the child to the end of the content list. return the parent (the calling object)"
idx <- length(contentList) + 1
contentList[[idx]] <<- content
return(.self)
},
findContentIndex = function(content) {
"Find the position of the content in the contentList or -1 if not found"
for (idx in seq_along(contentList)) {
if(identical(content, contentList[[idx]])) {
return(idx)
}
}
-1
},
removeContent = function(content) {
"Remove the specified content from this element"
index <- findContentIndex(content)
if ( index != -1){
contentList <<- contentList[- index]
} else {
stop("There is no such content belonging to this Element")
}
}
)
)
foo <- Element$new("foo")
foo$addContent(Element$new("Bar"))
baz <- Element$new("Baz")
foo$addContent(baz)
foo$removeContent(baz)
tryCatch(
{
foo$removeContent(baz)
},
error=function(cond) {
print(paste("Expected this error, ", cond$message))
}
)
Element不使用显式索引的方法是使用sapply(contentList,idential,content)
查找匹配的对象。我们可以简化整个类定义,保留功能,如下所示:
元素列表()
#>
#> [[2]]
#>类“元素”的引用类对象
#>字段“m_名称”:
#>[1]“Baz”
#>字段“内容列表”:
#>列表()
foo$removeContent(baz)
福
#>类“元素”的引用类对象
#>字段“m_名称”:
#>[1]“foo”
#>字段“内容列表”:
#> [[1]]
#>类“元素”的引用类对象
#>字段“m_名称”:
#>[1]“酒吧”
#>字段“内容列表”:
#>列表()
使用您的tryCatch
:
tryCatch(
{
foo$removeContent(baz)
},
错误=函数(cond){
打印(粘贴(“预期此错误,”,cond$消息))
}
)
#>[1]“应为此错误,未找到内容”
由(v0.3.0)于2020年4月8日创建。如果您提供了样本数据和所需的输出,将更容易提供帮助。请参见R标记页面的标题