Access lapply index names inside FUN
This basically uses the same workaround as Tommy, but with Map()
, there's no need to access global variables which store the names of list components.
> x <- list(a=11, b=12, c=13)
> Map(function(x, i) paste(i, x), x, names(x))
$a
[1] "a 11"
$b
[1] "b 12"
$c
[1] "c 13
Or, if you prefer mapply()
> mapply(function(x, i) paste(i, x), x, names(x))
a b c
"a 11" "b 12" "c 13"
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.