在lapply中进行deparse(substitute(x))? [英] deparse(substitute(x)) in lapply?

查看:99
本文介绍了在lapply中进行deparse(substitute(x))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用在lapply中使用标准deparse(substitute(x))技巧的函数.不幸的是,我只是得到循环的理由.这是我完全无用的可复制示例:

I would like use a function that uses the standard deparse(substitute(x)) trick within lapply. Unfortunately I just get the argument of the loop back. Here's my completely useless reproducible example:

# some test data
a <- 5
b <- 6 
li <- list(a1=a,b2=b)

# my test function
tf <- function(obj){
nm <- deparse(substitute(obj))
res <- list(myName=nm)
res
}

tf(a)
#returns
$myName
[1] "a"

这很好.如果我使用lapply,则会得到[[1L]]或匿名函数的x参数.

which is fine. If I use lapply I either get [[1L]] or the x argument of an anonymous function.

lapply(li,function(x) tf(x))
# returns
$a1
$a1$myName
[1] "x"


$b2
$b2$myName
[1] "x"

有什么办法获取以下内容?

Is there any way to obtain the following?

$a1
$a1$myName
[1] "a1"


$b2
$b2$myName
[1] "b1"

如果deparse(substitute(x))lapply上还有更多常规内容,我也很想知道.

If there's anything more general on deparse(substitute(x)) and lapply I'd also eager to know.

与使用匿名函数接受多个参数并因此可以使用对象的名称以及对象本身不起作用相比,此问题不起作用,因为tf函数将仅接受一个参数.因此在这里不起作用...

The problem as opposed to using an anonymous function that accepts multiple arguments and can thus use the name of the object and the object itself does not work because, the tf function will only accept one argument. So this does not work here...

推荐答案

可能的解决方案:

lapply(li, function(x) {
  call1 <-  sys.call(1)
  call1[[1]] <- as.name("names")
  call1 <- call1[1:2]
  nm <- eval(call1)
  y <- deparse(substitute(x))
  y <- gsub("\\D", "", y)
  y <- as.numeric(y)
  list(myname=nm[y])
})

这篇关于在lapply中进行deparse(substitute(x))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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