How to run a loop on the elements in workspace?

前端 未结 2 549
天涯浪人
天涯浪人 2021-01-22 11:07
> ls()
 [1] \"A\"          \"anorex.1\"   \"anorexia\"   \"B\"          \"byMonth\"    \"C\"          \"clotting\"  
 [8] \"counts\"     \"d\"          \"D\"                  


        
相关标签:
2条回答
  • 2021-01-22 11:48

    You can use get() for this. Like:

    for (i in ls()) {
      print(get(i))
    }
    
    0 讨论(0)
  • 2021-01-22 12:01

    Your loop only uses a character name, so R thinks it's just a character vector. You need to get the object itself. You can use mget() to get multiple objects in a given environment, in a list, from a character vector. That means we can pass it ls(). Then we can run through that list and get the class.

    lapply(mget(ls()), class)
    

    I use lapply() because it is entirely possible that some objects have more than one class.

    If you want to know other attributes/information about the object, write a function.

    f <- function(x) list(dim = dim(x), class = class(x))
    lapply(mget(ls()), f)
    
    0 讨论(0)
提交回复
热议问题