隐藏ls()结果中的函数名称-更快地找到变量名称 [英] Hiding function names from ls() results - to find a variable name more quickly

查看:70
本文介绍了隐藏ls()结果中的函数名称-更快地找到变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们定义了数十个函数(可能是开发一个新程序包)时,很难通过ls()命令在许多函数名称中找到特定变量的名称.

When we have defined tens of functions - probably to develop a new package - it is hard to find out the name of a specific variable among many function names through ls() command.

在大多数情况下,我们不是在寻找函数名称-我们已经知道它们存在-但我们想查找分配给变量的名称是什么.

In most of cases we are not looking for a function name - we already know they exist - but we want to find what was the name we assigned to a variable.

任何解决它的想法都受到高度赞赏.

Any idea to solve it is highly appreciated.

推荐答案

如果您想要一个函数来执行此操作,则需要在ls()所在的环境中进行一些操作.在正常情况下,下面的实现将通过在函数的父框架中列出对象来工作,如果在顶层调用,它将是全局环境.

If you want a function to do this, you need to play around a bit with the environment that ls() looks in. In normal usage, the implementation below will work by listing objects in the parent frame of the function, which will be the global environment if called at the top level.

lsnofun <- function(name = parent.frame()) {
    obj <- ls(name = name)
    obj[!sapply(obj, function(x) is.function(get(x)))]
}

> ls()
[1] "bar"           "crossvalidate" "df"           
[4] "f1"            "f2"            "foo"          
[7] "lsnofun"       "prod"         
> lsnofun()
[1] "crossvalidate" "df"            "f1"           
[4] "f2"            "foo"           "prod"

我已经写了这个,所以如果需要在一系列嵌套函数调用中以这种方式调用,可以传入ls()name参数.

I've written this so you can pass in the name argument of ls() if you need to call this way down in a series of nested function calls.

请注意,在测试对象是否为函数时,还需要get()ls()命名的对象.

Note also we need to get() the objects named by ls() when we test if they are a function or not.

这篇关于隐藏ls()结果中的函数名称-更快地找到变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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