How to use with/within inside a function?

前端 未结 3 1464
[愿得一人]
[愿得一人] 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:42

    Anything that is passed to a function must be an object, a string or a number. There are two problems with this:

    1. In this case you're trying to pass "a" as an object, when you should really be passing it like a string.
    2. with(obj, ls())) will return to the functions environment (function scoping) and not the screen unless you tell it to print.

    What you want is more like:

    foo <- function(obj, col) {
           print(with(obj, ls()))
           with(obj, print(obj[[col]]))
        }
    
    foo(df, "a")
    

    Or if you're only looking for the one column to be printed:

    foo <- function(obj, col) {
               with(obj, print(obj[[col]]))
            }
    
    foo(df, "a")
    

提交回复
热议问题