并不是说我会推荐这个,但这里有一种可能不太麻烦的方法来确保您不会从包含重复名称的列表中提取元素:
## Define a method for `[[` that first checks the list x for repeated names
`[[.CC` <- function(x,i,j,...,exact=TRUE) {
if(!length(unique(names(x))) == length(names(x))) {
stop("List contains multiple elements with the same name")
} else {
NextMethod()
}
}
## Write a function that prepends the class that triggers the method above
CC <- function(X) {
class(X) <- c("CC", class(X))
X
}
## Try it out
l <- list(a=1, a="a")
m <- list(a=1, b="a")
CC(l)[["a"]]
# Error in `[[.CC`(CC(l), "a") :
# List contains multiple elements with the same name
CC(m)[["a"]]
# [1] 1