Robert Kubrick - 6 months ago 114

R Question

Is there a way to get the list index name in my lapply() function?

`n = names(mylist)`

lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })

I asked before if it's possible to preserve the index names in the lapply()

Answer

Unfortunately, `lapply`

only gives you the elements of the vector you pass it.
The usual work-around is to pass it the names or indices of the vector instead of the vector itself.

But note that you can always pass in extra arguments to the function, so the following works:

```
x <- list(a=11,b=12,c=13) # Changed to list to address concerns in commments
lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x))
```

Here I use `lapply`

over the indices of `x`

, but also pass in `x`

and the names of `x`

. As you can see, the order of the function arguments can be anything - `lapply`

will pass in the "element" (here the index) to the first argument *not* specified among the extra ones. In this case, I specify `y`

and `n`

, so there's only `i`

left...

Which produces the following:

```
[[1]]
[1] "a 11"
[[2]]
[1] "b 12"
[[3]]
[1] "c 13"
```

**UPDATE** Simpler example, same result:

```
lapply(seq_along(x), function(i) paste(names(x)[[i]], x[[i]]))
```

Here the function uses "global" variable `x`

and extracts the names in each call.