How do I initialize an empty list for use in a for-loop or function?
Sometimes I’m writing a for-loop (I know, I know, don’t use for-loops, but sometimes it’s just easier. I’m a little less good at apply functions than I’d like to be) and I know I’ll need to store the output in a list. Once in a while, the new list will be the same size as an existing one, but more often, I just need to start from scratch, knowing only the number of elements I want to include.
This isn’t a totally alien thing to need to do––it’s pretty familiar if you’re used to initializing empty vectors before for-loops. There’s a whole other debate to be had about whether or not it’s acceptable to start with a truly empty vector and append to it on every iteration of the loop or whether you should always know the length beforehand, but I’ll just focus on the latter case for now.
Anyway, initializing a vector of a given length is easy enough; I usually do it like this:
> desired_length <- 10 # or whatever length you want > empty_vec <- rep(NA, desired_length)
I couldn’t immediately figure out how to replicate this for a list, though. The solution turns out to be relatively simple, but it’s just different enough that I can never seem to remember the syntax. This post is more for my records than anything, then.
Initializing an empty list turns out to have an added benefit over my rep(NA) method for vectors; namely, the list ends up actually empty, not filled with NA’s. Confusingly, the function to use is “vector,” not “list.”
> desired_length <- 10 # or whatever length you want > empty_list <- vector(mode = "list", length = desired_length) > str(empty_list) List of 10 $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL $ : NULL
Voilà, an empty list. No restrictions on the data type or structure of the individual list elements. Specify the length easily. Useful for loops, primarily, but may have other applications I haven’t come across yet.