How to use with/within inside a function?

前端 未结 3 1466
[愿得一人]
[愿得一人] 2020-12-10 07:30

I\'m struggling to understand why does this doesn\'t work.

df <- data.frame(a=1:10, b=1:10)

foo <- function(obj, col) {
   with(obj, ls())
   with(obj         


        
3条回答
  •  借酒劲吻你
    2020-12-10 07:34

    In function argument col is evaluated before using in function with (that opposite to interactive use). Here you have two solutions to this problem.

    foo1 <- function(obj, col) {
              with(obj, print(eval(col)))
            }
    foo1(mydf, quote(a))# here you have to remember to quote argument
    
    
    foo2 <- function(obj, col) {
              col <- as.expression(as.name(substitute(col)))#corrected after DWIN comment
              with(obj, print(eval(col)))
            }
    foo2(mydf, a)# this function does all necessary stuff
    

提交回复
热议问题