[R] get element of list with default?

Hadley Wickham h.wickham at gmail.com
Tue Apr 15 18:33:26 CEST 2014


You really want to use the names of the list since lists can contain
null.  I'd recommend something more like:

getElement <- function(x, i, default) {
  if (i %in% names(x)) return(x[[i]])
  default
}

Hadley

On Tue, Apr 15, 2014 at 10:53 AM, Spencer Graves
<spencer.graves at structuremonitoring.com> wrote:
> Hello:
>
>
>       Do you know of a simple function to return the value of a named
> element of a list if that exists, and return a default value otherwise?
>
>
>       It's an easy function to write (e.g., below).  I plan to add this to
> the "Ecfun" package unless I find it in another CRAN package.
>
>
>       Thanks,
>       Spencer
>
>
>     getElement <- function(element, default, list){
> #       get element of list;  return elDefault if absent
>         El <- list[[element]]
>         if(is.null(El)){
>             El <- default
>         }
>         El
>     }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
http://had.co.nz/




More information about the R-help mailing list