[R] Accessing list names in lapply
Bjarke Christensen
Bjarke.Christensen at sydbank.dk
Thu Nov 19 13:27:08 CET 2009
Hi,
When using lapply (or sapply) to loop over a list, can I somehow access the
index of the list from inside the function?
A trivial example:
df1 <- split(
x=rnorm(n=100, sd=seq(from=1, to=10, each=10)),
f=letters[seq(from=1, to=10, each=10)]
)
str(df1)
#List of 10
# $ a: num [1:10] -0.801 0.418 1.451 -0.554 -0.578 ...
# $ b: num [1:10] -2.464 0.279 4.099 -2.483 1.921 ...
# $ c: num [1:10] -1.14 -1.773 2.512 -2.072 -0.904 ...
# $ d: num [1:10] 2.109 1.243 0.627 -2.343 -6.071 ...
#...
par(mfcol=c(5,2))
lapply(df1, plot)
This plots each element of the list, but the label on the vertical axis is
X[[0L]] (as expected from the documentation in ?lapply). I'd like the
heading for each plot to be the name of that item in the list. This can be
achieved by using a for-loop:
for (i in names(df1)) plot(df1[[i]], ylab=i)
but can it somehow be achieved bu using lapply? I would be hoping for
something like
lapply(df1, function(x) plot(x, ylab=parent.index()))
or some way to parse the index number out of the call, using match.call()
or something like that.
Thanks in advance for any comments,
Bjarke Christensen
More information about the R-help
mailing list