R get name of list element in lapply

Lists

Lists are a key data type in R but can be avoided by beginners due to being a bit harder to work with. The do however hold the key to many of Rs more advanced features.

The apply family functions

We move now to apply functions. We will look at the three most popular: lapply[], vapply[] and apply[]

lapply[]

List apply will take each element of your list, call a function upon it, then return a list of the results. lapply[] can be really useful to write compact, understandable code.

It is often used to replace what would be for loops in other languages, and offers benefits like better memory management and vectorisation. Its one reason some cite use of for[] loops in R code as bad R-style, although there is still some scope for them.

Guide to using lapply[]

Lets build up an lapply function, that will work on a list of data.frames.

  1. Choose what you want the lapply[] function to iterate across. In this example we have a list of data.frames, a_list_of_df

  2. Choose our function. This will operate on each element,

  3. Test the function on one element i.e.the contents of a_list_of_df[[x]] NOT a_list_of_df[x]. Once happy we know it should work on the entire list.

  4. Any constant arguments get added to the end of the lapply - e.g.is you are using sum[] you may want all the sum functions to ignore NA e.g. sum[x, na.rm = TRUE]

  5. Construct the full function result

Chủ Đề