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

前端 未结 2 1738
余生分开走
余生分开走 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:36

    So far as I know, you would need to store the expression in a string. Then you can parse it with getParseData:

    txt <- "z<-x+y"
    
    sf <- srcfile("txt")   
    df = getParseData(sf)    
    df$text[df$token=="SYMBOL"][2:3]
    

    For further edification, here is what the result of getParseData looks like in its entirety:

       line1 col1 line2 col2 id parent       token terminal text
    11     1    1     1    6 11      0        expr    FALSE     
    1      1    1     1    1  1      3      SYMBOL     TRUE    z
    3      1    1     1    1  3     11        expr    FALSE     
    2      1    2     1    3  2     11 LEFT_ASSIGN     TRUE   <-
    10     1    4     1    6 10     11        expr    FALSE     
    4      1    4     1    4  4      6      SYMBOL     TRUE    x
    6      1    4     1    4  6     10        expr    FALSE     
    5      1    5     1    5  5     10         '+'     TRUE    +
    7      1    6     1    6  7      9      SYMBOL     TRUE    y
    9      1    6     1    6  9     10        expr    FALSE    
    

提交回复
热议问题