rexpressionscoped

Is there a scoped environment fot the language R beyond the environment function attach to work with data.frames?


I've a larger script in the programming language R and work with tables. I've a table base.tab

  ID      LAT      LON ALT.ORTHO TYPE TYPE.ID
1  1 53.75447 12.51539   46.5555 LINE       1
2 10 53.75452 12.51565   46.5445 LINE       1
3 11 53.75452 12.51567   46.5365 LINE       1
4 12 53.75453 12.51570   46.5715 LINE       1
5 13 53.75453 12.51573   46.5785 LINE       1
6 14 53.75454 12.51576   46.6885 LINE       1

and want to shorten some expressions without using attach or subset. Instead of writing

base.tab.epos <-
     base.tab[(base.tab$TYPE == 'LINE') |
              (base.tab$TYPE == 'RAND'),  ] 

I want to use something in a scoped context like:

with(base.tab) do { 
    base.tab.epos <-
         base.tab[(TYPE == 'LINE') |
                  (TYPE == 'RAND'),  ] 
}

Is there an expression in the programming language R to do that?


Solution

  • R has with/within function which can achieve that.

    base.tab.epos <- base.tab[with(base.tab, TYPE == 'LINE' | TYPE == 'RAND'), ]
    

    Apart from that you can also have a look at dplyr which will allow you to refer to column names without using data$ every time.

    library(dplyr)
    base.tab.epos <- base.tab %>% filter(TYPE == 'LINE' | TYPE == 'RAND')