print list names when iterating lapply [duplicate]

大城市里の小女人 提交于 2019-12-11 03:04:30

问题


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)

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.


回答1:


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

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)



回答2:


The item names do not get passed to the second argument from lapply, only the values do. So if you wanted to see the names then the calling strategy would need to be different:

> abc <- function(nm, x) {
+   r <- mean(x)
+   print(nm)
+   return(r)
+ }
> 
> forl <- mapply(abc, names(dat.list), dat.list)
[1] "x"
[1] "y"
[1] "z"
[1] "a"


来源:https://stackoverflow.com/questions/27727590/print-list-names-when-iterating-lapply

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