Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over objects in global environment [duplicate]

I'm pretty new to R and trying to write a loop or a concise code for a simple task: checking the class of all the current objects in my Global Environment in R.

class(mydata)
#[1] "data.frame"
class(mylist)
#[1] "list"
class(mymatrix)
#[1] "matrix"
...

The following code worked, but what if I have many objects and I don't want to type all the names.

dflist <- list(mydata, mylist, mymatrix)
lapply(dflist,class)

I tried the following methods, none of them worked.

 #1
for (i in ls()){
  class(i)
}

 #2
for (i in ls()){
  lapply(i,class)
}

any solutions? Thanks.

like image 364
Eric Wang Avatar asked Apr 11 '26 20:04

Eric Wang


2 Answers

You could use mget which returns "a named list of objects". The function's first argument should be a character vector of object names, which is what ls() returns.

lapply(mget(ls()), class)
#$mydata
#[1] "data.frame"
# 
#$mylist
#[1] "list"
#
#$mymatrix
#[1] "matrix"
like image 146
markus Avatar answered Apr 14 '26 11:04

markus


Try eapply:

eapply(.GlobalEnv, class)
like image 42
G. Grothendieck Avatar answered Apr 14 '26 09:04

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!