在lapply中进行deparse(substitute(x))? [英] deparse(substitute(x)) in lapply?
问题描述
我想使用在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屋!