[R] get() within function

Thomas Mailund mailund at birc.au.dk
Thu Aug 18 13:00:37 CEST 2016


 
Hi Ivan,

ls() inside a function gives you the variables in the local scope. If you want to get the variables defined in the global scope you need to tell ls() that.

Check the difference between these three functions:

> foo <- function() ls()
> foo()

Returns character(0) because there are no local variables.

> bar <- function(x) ls()
> bar(1)

Returns “x” because ls() sees the function parameter

> baz <- function() ls(envir = .GlobalEnv)
> baz()

Returns all the variables in the global environment.

If you change your function foo() to this, it should work:


foo <- function() { 
  selected_names <- sapply(ls(.GlobalEnv), 
                           function(x) class(get(x))) %in% c("data.frame","list")
  df.list <- ls(.GlobalEnv)[selected_names] 
  dat.str <- select.list(choices=df.list, title="Select object") 
  dat <- get(dat.str) 
  str(dat) 
} 

Cheers
	Thomas






On 18 August 2016 at 12:21:33, Ivan Calandra (ivan.calandra at univ-reims.fr(mailto:ivan.calandra at univ-reims.fr)) wrote:

> Dear useRs,
>  
> For an interactive use, I am trying to write a function that looks for
> all data.frames and lists in the environment and ask the user to select
> one of them. I then run some operations on this object.
>  
> This is what I am trying:
>  
> foo <- function(){
> df.list <- ls()[sapply(ls(), function(x) class(get(x))) %in%
> c("data.frame","list")]
> dat.str <- select.list(choices=df.list, title="Select object")
> dat <- get(dat.str)
> str(dat)
> }
>  
> Let's say I have these three objects:
> vec <- 1:10
> mylist <- list(1:3)
> datf <- data.frame(var1=rnorm(10), var2=rnorm(10))
>  
> I would like the function to show me only mylist and datf in the dialog
> box. Everything works fine if I take the code out of the function, but
> when I run foo() I get this error:
> "Error in get(dat.str) : first argument incorrect"
>  
> Is there a problem with using get() within a function? Maybe a problem
> with environments?
>  
> Thank you in advance for any help!
> Ivan
>  
> --
> Ivan Calandra, PhD
> Scientific Mediator
> University of Reims Champagne-Ardenne
> GEGENAA - EA 3795
> CREA - 2 esplanade Roland Garros
> 51100 Reims, France
> +33(0)3 26 77 36 89
> ivan.calandra at univ-reims.fr
> --
> https://www.researchgate.net/profile/Ivan_Calandra
> https://publons.com/author/705639/
>  
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


More information about the R-help mailing list