Very confusing R feature - completion of list item names

后端 未结 2 1938
挽巷
挽巷 2021-01-15 04:03

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 &l         


        
相关标签:
2条回答
  • 2021-01-15 04:49

    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"]
    0 讨论(0)
  • 2021-01-15 04:57

    You can use [ or [[ instead.

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

    0 讨论(0)
提交回复
热议问题