As @ada-lovelace correctly points out, it's the $
operator that's the problem. Here's an idea. Let's redefine it! I am seriously considering loading the following code at the beginning of my programs.
`$` = function(obj, elem) {
idx = which(names(obj) == substitute(elem))
if (length(idx) != 1L) {
stop(paste0("Element `", substitute(elem), "` not found in object `", substitute(obj), "`."))
}
obj[[idx]]
}
Let's test it:
identical(mtcars$gear, mtcars[,"gear"]) # Works with data.frames
mtcars$gearx # Typo: error!
mylist = as.list(mtcars)
identical(mylist$gear, mylist[["gear"]]) # Works with lists
mylist$gearx # Typo: error!
It appears to work as intended.