Indexing a dataframe with $ inside a function?

后端 未结 3 705
生来不讨喜
生来不讨喜 2021-01-26 11:10

Many R textbooks encourage the use of $ to retrieve variables (columns) from data.frames^. However, I found that this does not work inside a function, and I can\'t figure out wh

3条回答
  •  太阳男子
    2021-01-26 12:01

    If you want to perfectly mimic the $ operator you can use [[ and set the parameter exact to FALSE to allow for partial matching.

    BOD <- data.frame(demand = 1:10)
    
    myFunc2 <- function(x, y) x[[y, exact = FALSE]]
    
    BOD$dem
    ## [1]  1  2  3  4  5  6  7  8  9 10
    
    BOD[["dem"]]
    ## NULL
    
    myFunc2(BOD, "dem")
    ## [1]  1  2  3  4  5  6  7  8  9 10
    

提交回复
热议问题