print list names when iterating lapply

12,661

Solution 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)

Solution 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"
Share:
12,661
forecaster
Author by

forecaster

Updated on July 17, 2022

Comments

  • forecaster
    forecaster almost 2 years

    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.