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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…