Re: [R] extract from a list of lists

2022-12-28 Thread Leonard Mada via R-help
Dear Terry, The following approach may be more suitable: fits <- lapply(argument, function) fits.df = do.call(rbind, fits); It works if all the lists returned by "function" have the same number of elements. Example: fits.df = lapply(seq(3), function(id) { list( beta =

Re: [R] extract from a list of lists

2022-12-27 Thread Bill Dunlap
I find your original sapply(List, function(element)element$name) easy to understand. However replacing sapply with vapply makes for more robust code. vapply requires you to supply the expected mode (type) and length of element$name and if any of the elements don't comply with that, vapply gives

Re: [R] extract from a list of lists

2022-12-27 Thread Therneau, Terry M., Ph.D. via R-help
Thanks everyone for prodding my gray matter, which seems to be getting stiffer as I approach 70 (< 90 days).  --  I'll continue to use the $ or [[ forms.   That will suffice. --  I thought there might be a base R variant, e.g. something like  extract( list, element-name); probably cross

Re: [R] extract from a list of lists

2022-12-27 Thread Bert Gunter
Well, I prefer Greg's approach, but if you want to avoid calls to $ or `[[` then you could do: unlist(fits)[ rep(names(fits[[1]]) == 'iter', length(fits))] Cheers, Bert On Tue, Dec 27, 2022 at 9:46 AM Greg Snow <538...@gmail.com> wrote: > > Another option is the map family of functions in the

Re: [R] extract from a list of lists

2022-12-27 Thread Greg Snow
Another option is the map family of functions in the purrr package (yes, this depends on another package being loaded, which may affect things if you are including this in your own package, creating a dependency). In map and friends, if the "function" is a string or integer, then it is taken as

Re: [R] extract from a list of lists

2022-12-27 Thread Greg Snow
Terry, I don't know if it is much cleaner or not, but you can use: sapply(fits, `[[`, 'iter') This calls the `[[` function (to extract list elements) on each element of the top list, with the extra argument of `iter` to say which element. On Tue, Dec 27, 2022 at 10:16 AM Therneau, Terry M.,

[R] extract from a list of lists

2022-12-27 Thread Therneau, Terry M., Ph.D. via R-help
I not uncommonly have the following paradym    fits <- lapply(argument, function) resulting in a list of function results.   Often, the outer call is to mclapply, and the function encodes some long calculation, e.g. multiple chains in an MCMC. Assume for illustration that each function returns