遍历lapply时打印列表名称 [英] print list names when iterating lapply
问题描述
我在名为dat.list的列表名称中有一个时间序列(x,y,z和a).我想使用lapply
将函数应用于此列表.有没有一种方法可以在lapply中完成每次迭代后打印元素名称,即x,y,z和a.下面是可复制的示例.
I have a time series (x,y,z and a) in a list name called dat.list. I would like to apply a function to this list using lapply
. Is there a way that I can print the element names i.e., x,y,z and a after each iteration is completed in lapply. Below is the reproducible example.
## Create Dummy Data
x <- ts(rnorm(40,5), start = c(1961, 1), frequency = 12)
y <- ts(rnorm(50,20), start = c(1971, 1), frequency = 12)
z <- ts(rnorm(50,39), start = c(1981, 1), frequency = 12)
a <- ts(rnorm(50,59), start = c(1991, 1), frequency = 12)
dat.list <- list(x=x,y=y,z=z,a=a)
## forecast using lapply
abc <- function(x) {
r <- mean(x)
print(names(x))
return(r)
}
forl <- lapply(dat.list,abc)
基本上,我想每次在这些元素上执行函数时都打印元素名称x,y,z.当我运行上面的代码时,我会得到空值.
Basically, I would like to print the element names x,y,z and a every time the function is executed on these elements. when I run the above code, I get null values printed.
推荐答案
您可以使用一些深层挖掘(我是从SO的另一个答案中获得的-我将尝试找到链接),并执行以下操作:
You can use some deep digging (which I got from another answer on SO--I'll try to find the link) and do something like this:
abc <- function(x) {
r <- mean(x)
print(eval.parent(quote(names(X)))[substitute(x)[[3]]])
return(r)
}
forl <- lapply(dat.list, abc)
# [1] "x"
# [1] "y"
# [1] "z"
# [1] "a"
forl
# $x
# [1] 5.035647
#
# $y
# [1] 19.78315
#
# $z
# [1] 39.18325
#
# $a
# [1] 58.83891
我们可以像这样(在@con>的名称中只是lapply
)(类似于@BondedDust所做的事情)(但会丢失输出中的列表名称):
Our you can just lapply
across the names of the list
(similar to what @BondedDust did), like this (but you lose the list names in the output):
abc <- function(x, y) {
r <- mean(y[[x]])
print(x)
return(r)
}
lapply(names(dat.list), abc, y = dat.list)
这篇关于遍历lapply时打印列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!