Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - get all variables created from function call

Tags:

r

This is crazy, and just out of intellectual curiosity: Can I run a function in R in such a way that after the function completes I can get all variables created when the function executed? So the ability to look into a function right before it returned? I don't mean entering the function in debug mode.

like image 481
SFun28 Avatar asked Sep 02 '11 03:09

SFun28


People also ask

How do I see all variables in R?

You can use ls() to list all variables that are created in the environment. Use ls() to display all variables. pat = " " is used for pattern matching such as ^, $, ., etc.

Which R function should you use to get the variable type?

Getting type of different data types in R Programming – typeof() Function. typeof() function in R Language is used to return the types of data used as the arguments.

How do I save a list of objects in R?

To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function. In each case, the first argument should be the name of the R object you wish to save. You should then include a file argument that has the file name or file path you want to save the data set to.

How do I view values in R?

If you want to just view the variable's contents, you can try clicking the icon on the right side of the workspace, e.g. Clicking on that icon at the right would open the mtcars dataset in the Data Viewer.


1 Answers

To get all variables and their values as a list you could use the last line of the function in this example:

myFunction=function(){
  a="lolcat"
  b=data.frame(firstCol=1:3,secondCol=letters[1:3])
  d=list()
  d[["someName"]]=10:13
  sapply(ls(),function(x)get(x),simplify=F,USE.NAMES=T)
}

myResults=myFunction()

myResults

Output:

$a
[1] "lolcat"

$b
  firstCol secondCol
1        1         a
2        2         b
3        3         c

$d
$d$someName
[1] 10 11 12 13
like image 64
Hauberg42 Avatar answered Sep 21 '22 20:09

Hauberg42