79289852

Date: 2024-12-18 02:50:13
Score: 1
Natty:
Report link

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.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @ada-lovelace
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Alex Strashny