I was wondering what the best way is to use the lapply famliy (or plyr) family of functions to take a vector, apply a function to the elements, and return a list whose names are the same as the values supplied in the first argument vector. So, for example if i do:
lapply(letters[1:3], function(x) NULL)
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
I'd like to return, instead of [[1]], [[2]], [[3]] as the name (or rather just plain index) of the list, the letters "a", "b", and "c" as the names of the output list.
I know from here that I can do this (How to create a list with names but no entries in R/Splus?) to create the list beforehand with the right names, but I am wondering if I can do this without pre-creating the list with the right names.
Thanks, Matt
sapply
has a USE.NAMES
argument that will do what you want:
sapply(letters[1:3], function(x) NULL, simplify=FALSE, USE.NAMES=TRUE)
# $a
# NULL
# $b
# NULL
# $c
# NULL
As Josh O'Brien notes in the comments--and as you've figured out--simplify=FALSE
prevents the output from being reduced to a simpler data structure, keeping the results consistent with what you'd get with lapply
(well, besides the names of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With