Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very confusing R feature - completion of list item names

Tags:

r

I found a very suprising and unpleasant feature of R - it completes list item names!!! See the following code:

a <- list(cov_spring = "spring")
a$cov <- c()
a$cov
# spring  ## I expect it to be empty!!! I've set it empty!
a$co
# spring
a$c 

I don't know what to do with that.... I need to be able to set $cov to NULL and have $cov_spring there at the same time!!! And use $cov separately!! This is annoying!

My question:

  1. What is going on here? How is this possible, what is the logic behind?
  2. Is there some easy fix, how to turn this completion off? I need to use list items cov_spring and cov independently as if they are normal variables. No damn completion please!!!
like image 274
Tomas Avatar asked Jan 24 '26 20:01

Tomas


2 Answers

From help("$"):

'x$name' is equivalent to 'x[["name", exact = FALSE]]'

When you scroll back and read up on exact=:

exact: Controls possible partial matching of '[[' when extracting by
      a character vector (for most objects, but see under
      'Environments').  The default is no partial matching.  Value
      'NA' allows partial matching but issues a warning when it
      occurs.  Value 'FALSE' allows partial matching without any
      warning.

So this provides you partial matching capability in both $ and [[ indexing:

mtcars$cy
#  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
mtcars[["cy"]]
# NULL
mtcars[["cy", exact=FALSE]]
#  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

There is no way I can see of to disable the exact=FALSE default for $ (unless you want to mess with formals, which I do not recommend for the sake of reproducibility and consistent behavior).

Programmatic use of frames and lists (for defensive purposes) should prefer [[ over $ for precisely this reason. (It's rare, but I have been bitten by this permissive behavior.)

Edit:

For clarity on that last point:

  • mtcars$cyl becomes mtcars[["cyl"]]
  • mtcars$cyl[1:3] becomes mtcars[["cyl"]][1:3]
  • mtcars[,"cy"] is not a problem, nor is mtcars[1:3,"cy"]
like image 57
r2evans Avatar answered Jan 26 '26 09:01

r2evans


You can use [ or [[ instead.

a["cov"] will return a list with a NULL element. a[["cov"]] will return the NULL element directly.

like image 42
Steven Hibble Avatar answered Jan 26 '26 08:01

Steven Hibble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!