Custom R Functions

From Bradwiki
Revision as of 20:34, 11 April 2021 by Bradley Monk (talk | contribs) (Created page with "Custom R Programming Language Functions ==Clear All Variables From Workspace Except== MATLAB has a built-in method to clear all variables from the current workspace environ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Custom R Programming Language Functions


Clear All Variables From Workspace Except

MATLAB has a built-in method to clear all variables from the current workspace environment, except for one or more specified variables. This can be done simply by typing...

   >> -clearvars except VAR1 VAR2 ETC

I've created the following function to perform the same operation in R...

   > rx<-function(S){rm(list=setdiff(ls(.GlobalEnv),c("rx",S)),envir=.GlobalEnv)}

This function can be inserted near the top of a script, and evaluated for (re)use later on in the script. This will allow the user to clear all environmental variables from the workspace except for the subset of variables that are required later on in the script. For example...


   a <- c(1, 2, 3)
   b <- c(2, 3, 4)
   c <- c(3, 4, 5)
   d <- c(4, 5, 6)
   e <- c(5, 6, 7)
   f <- c(6, 7, 8)
   g <- cbind(a,b)
   h <- cbind(c,d)
   i <- cbind(e,f)
   j <- cbind(g,h,i)
   k <- rbind(g,h,i)
   
   rx(c("j","k"))

this will clear