如何在R(替代)中获取变量的名称? [英] How to get name of variable in R (substitute)?

查看:47
本文介绍了如何在R(替代)中获取变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过几个函数传递变量,而在最后一个函数中,我想获取原始变量的名称.但似乎 R 中的替代函数仅在本地"环境中查看,或者仅用于上一级.好吧,让我用代码解释一下:

I stacked with trying to pass variable through few functions, and on the final function I want to get the name of the original variable. But it seems like substitute function in R looked only in "local" environment, or just for one level up. Well, let me explain it by code:

fun1 <- function (some_variable) {deparse(substitute(some_variable)}
fun2 <- function (var_pass) { fun1 (var_pass) }
my_var <- c(1,2) # I want to get 'my_var' in the end
fun2 (my_var) # > "var_pass"

好吧,似乎我们打印了只传递给 fun1 的变量名称.替代品的文档告诉我们,我们可以使用 env 参数来指定我们可以查看的位置.但是通过传递 .Global.BaseNamespaceEnv 作为替代参数,我得到了更奇怪的结果 - "some_variable"

Well, it seems like we printing the name of variable that only pass to the fun1. Documentation of the substitute tells us, that we can use env argument, to specify where we can look. But by passing .Global or .BaseNamespaceEnv as an argument to substitute I got even more strange results - "some_variable"

我相信答案就在这个函数中,使用 env 参数,所以,请你解释一下它是如何工作的,以及我如何才能得到我需要的东西.提前致谢!

I believe that answer is in this function with using env argument, so, could you please explain me how it works and how can I get what I need. Thanks in advance!

推荐答案

我建议您考虑将可选的名称值传递给这些函数.我这样说是因为您似乎真的想将名称用作最终结果的标签;所以真正重要的并不是变量本身,而是它的名称.你可以这样做

I suggest you consider passing optional name value to these functions. I say this because it seems like you really want to use the name as a label for something in the end result; so it's not really the variable itself that matters so much as its name. You could do

fun1 <- function (some_variable, name=deparse(substitute(some_variable))) {
    name
}
fun2 <- function (var_pass, name=deparse(substitute(var_pass))) { 
    fun1 (var_pass, name) 
}
my_var <- c(1,2)

fun2(my_var)
# [1] "my_var"

fun1(my_var)
# [1] "my_var"

这样,如果您最终有一些奇怪的变量名称以及如何为结果提供更好的名称,您至少可以选择.默认情况下,它应该可以执行您想要的操作,而无需使用 name 参数.

This way if you end up having some odd variable name and what to give a better name to a result, you at least have the option. And by default it should do what you want without having to require the name parameter.

这篇关于如何在R(替代)中获取变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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