deparse(substitute(x)) in lapply?

谁都会走 提交于 2019-12-18 12:13:31

问题


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"

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"

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

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. So this does not work here...


回答1:


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


来源:https://stackoverflow.com/questions/18508790/deparsesubstitutex-in-lapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!