Disabling partial variable names in subsetting data frames

后端 未结 1 1419
难免孤独
难免孤独 2021-01-21 16:48

I have just discovered that R will allow me to use partial variable names to subset data frames, as long as they are uniquely defined. I find this dangerous and am wondering if

相关标签:
1条回答
  • 2021-01-21 17:17

    No, not really. You can use options(warnPartialMatchDollar=TRUE) to get a warning when you do this (I'm using r-devel ... I think this is in the released version??), and you could use options(warn=2) to upgrade warnings to errors (but this would upgrade all warnings to errors ...)

    I believe the standard advice/best practice is to use [[-indexing instead

    myframe <- data.frame(othervar=1:3, myvar=4:6)
    myframe$myv
    ## [1] 4 5 6   (no problem)
    myframe$wrong
    ## NULL
    
    options(warnPartialMatchDollar=TRUE)
    myframe$myv
    ## [1] 4 5 6
    ## Warning message:
    ## In `$.data.frame`(myframe, myv) :
    ##   Partial match of 'myv' to 'myvar' in data frame
    options(warn=2) ## upgrade warnings to errors
    myframe$myv
    ## Error in `$.data.frame`(myframe, myv) : 
    ##   (converted from warning) Partial match of 'myv' to 'myvar' in data frame
    
    myframe[["myv"]]
    ## NULL
    
    0 讨论(0)
提交回复
热议问题