Passing a variable name to a function in R

前端 未结 4 856
悲&欢浪女
悲&欢浪女 2020-12-02 07:25

I\'ve noticed that quite a few packages allow you to pass symbol names that may not even be valid in the context where the function is called. I\'m wondering how this works

4条回答
  •  执念已碎
    2020-12-02 08:04

    I've recently discovered what I think is a better approach to passing variable names.

    a <- data.frame(x = 1:10, y = 1:10)
    
    b <- function(df, name){
        eval(substitute(name), df)
    }
    
    b(a, x)
      [1]  1  2  3  4  5  6  7  8  9 10
    

    Update The approach uses non standard evaluation. I began explaining but quickly realized that Hadley Wickham does it much better than I could. Read this http://adv-r.had.co.nz/Computing-on-the-language.html

提交回复
热议问题