Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lapply over vector, use values as output list names [duplicate]

Tags:

r

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

like image 630
mpettis Avatar asked Sep 17 '13 15:09

mpettis


1 Answers

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).

like image 54
Peyton Avatar answered Sep 28 '22 09:09

Peyton