Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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?

1 Answer

0 votes
by

To get the type of variable, you can use the get function to obtain the value rather than the character name of the object.

In your case:

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(get((i))))    #prints 'character'

}

Output:

[1] "closure"

[1] "double"

[1] "list"

[1] "list"

[1] "double"

[1] "list"

[1] "closure"

[1] "list"

[1] "closure"

[1] "list"

[1] "double"

[1] "character"

[1] "list"

[1] "list"

[1] "list"

[1] "list"

[1] "character"

[1] "character"

[1] "list"

[1] "list"

[1] "double"

[1] "closure"

[1] "list"

[1] "list"

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...