On Apr 15, 2014, at 11:22 AM, Marc Schwartz <marc_schwa...@me.com> wrote:
> On Apr 15, 2014, at 10:53 AM, Spencer Graves > <spencer.gra...@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 >> } > > > Hi Spencer, > > I don't know of a function elsewhere, but you can probably simplify the above > with: > > getElement <- function(element, default, list) { > ifelse(is.null(list[[element]]), default, list[[element]]) > } > > > MyList <- list(L1 = 1, L2 = 2) > >> MyList > $L1 > [1] 1 > > $L2 > [1] 2 > > > >> getElement("L1", 5, MyList) > [1] 1 > >> getElement("L2", 5, MyList) > [1] 2 > >> getElement("L3", 5, MyList) > [1] 5 > > > You might want to think about the ordering of the function arguments, given > typical use, for ease of calling it. For example: > > getElement <- function(list, element, default = SomeValue) > > Another consideration is that the above function will only get the element if > it is a 'first level' element in the list. If it is in a sub-list of the main > list, you would need to think about a recursive approach of some type, along > the lines of what ?rapply does. > > Regards, > > Marc Schwartz Spencer, A quick heads up here. I forgot, that there is already a function called getElement() in base R which appears to be designed to handle S4 objects and slots, lacking the default return value however, where it returns NULL if the 'name' element is not present: > getElement function (object, name) { if (isS4(object)) slot(object, name) else object[[name, exact = TRUE]] } <bytecode: 0x100905870> <environment: namespace:base> Thus, I would suggest calling your variant something else, or wrap the default function in your version, if you need/want to handle S4 objects and slots. Regards, Marc ______________________________________________ R-help@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.