Custom R Functions: Difference between revisions

From bradwiki
Jump to navigation Jump to search
(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...")
 
mNo edit summary
 
Line 29: Line 29:
     rx(c("j","k"))
     rx(c("j","k"))


this will clear
Calling <code>rx()</code> will clear all variables from the workspace except for variables <code>j</code> and <code>k</code>.





Latest revision as of 21:37, 11 April 2021

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"))

Calling rx() will clear all variables from the workspace except for variables j and k.