使用对象名称作为R中的列表名称 [英] Use object names as list names in R

查看:187
本文介绍了使用对象名称作为R中的列表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当然可以这样手动命名列表中的对象:

Of course I could name the objects in my list all manually like this:

    #create dfs
    df1<-data.frame(a=sample(1:50,10),b=sample(1:50,10),c=sample(1:50,10))
    df2<-data.frame(a=sample(1:50,9),b=sample(1:50,9),c=sample(1:50,9))
    df3<-data.frame(a=sample(1:50,8),b=sample(1:50,8),c=sample(1:50,8))

    #make them a list
    list.1<-list(df1=df1,df2=df2,df3=df3)

但是,如果我说50个长名称的对象,那么这将花费很多精力. 那么,有什么方法可以自动执行此操作,并使列表中的名称与外部对象相同?

But it makes a lot of work if I have let's say 50 objects with long names. So is there any way to automate this and make the names inside the list the same as the outside objects?

推荐答案

查找名称,然后调用mget.
如果每个变量的名称都有一个模式,那么这很简单.

Find the names, then call mget.
If there is a pattern to the names of each individual variable, then this is straightforward.

var_names <- paste0("df", 1:3)
mget(var_names, envir = globalenv())  #or maybe envir = parent.frame()

如果命名系统更复杂,则可以使用正则表达式来查找它们,例如使用

If the naming system is more complicated, you can use regular expressions to find them, using something like

var_names <- ls(envir = globalenv(), pattern = "^df[[:digit:]]+$")

这篇关于使用对象名称作为R中的列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆