Get type of all variables

user1625066 picture user1625066 · Oct 2, 2012 · Viewed 327.8k times · Source

In R, I'd like to retrieve a list of global variables at the end of my script and iterate over them. Here is my code

#declare a few sample variables
a<-10
b<-"Hello world"
c<-data.frame()

#get all global variables in script and iterate over them
myGlobals<-objects()
for(i in myGlobals){
  print(typeof(i))     #prints 'character'
}

My problem is that typeof(i) always returns character even though variable a and c are not character variables. How can I get the original type of variable inside the for loop?

Answer

James picture James · Oct 2, 2012

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"