简体   繁体   English

在lapply?deparse(substitute(x))?

[英]deparse(substitute(x)) in lapply?

I would like use a function that uses the standard deparse(substitute(x)) trick within lapply . 我想使用一个在deparse(substitute(x))中使用标准deparse(substitute(x))技巧的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"

which is fine. 这很好。 If I use lapply I either get [[1L]] or the x argument of an anonymous function. 如果我使用lapply我得到[[1L]]或匿名函数的x参数。

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"

If there's anything more general on deparse(substitute(x)) and lapply I'd also eager to know. 如果在deparse(substitute(x))lapply上有更一般的东西,我也渴望知道。

EDIT: 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. 编辑:问题,而不是使用接受多个参数的匿名函数,因此可以使用对象的名称和对象本身不起作用,因为, tf函数只接受一个参数。 So this does not work here... 所以在这里不起作用......

A possible solution : 可能的解决方案:

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])
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM