How to obtain all the variables in an R code expression?

前端 未结 2 1774
余生分开走
余生分开走 2021-01-14 09:07

How can an expression in R be decoded to get all the variables involved?

For example if you have:

z<-x+y;

get_all_variables(z);

[1] \'x\' \'y\'
         


        
2条回答
  •  误落风尘
    2021-01-14 09:26

    You can use all.vars, but you need to quote your expression:

    all.vars(quote(x + y))
    # [1] "x" "y"
    

    You can't just use z as you describe it contains an evaluated expression (i.e. the result of the expression), not the expression itself. You can write a function that removes one step:

    get_all_variables <- function(expr) all.vars(substitute(expr))
    get_all_variables(x + y)
    # [1] "x" "y"
    

    But you will not be able to recover the expression from z, unless you create z by z <- quote(x + y) or some such.

    If you have the expression in a string, then you can use @sunny's technique combined with all.vars:

    all.vars(parse(text="z <- x + y"))
    # [1] "z" "x" "y"
    

    Though obviously you get z as well. As always, don't evaluate arbitrary text with parse in case someone Bobby Tables you.

提交回复
热议问题