Description Usage Arguments Details Value Author(s) See Also Examples
Get element name of object. If object does not
have an element name, return default.
If the name element of object is NULL the result
depends on warn.NULL: If TRUE, issue a warning and
return default. Otherwise, return NULL
1 2 | getElement2(object, name=1, default=NA, warn.NULL=TRUE,
envir=list(), returnName)
|
object |
object from which to extract component |
name |
Name or index of the element to extract |
default |
default value if |
warn.NULL |
logical to decide how to treat cases where |
envir |
Supplemental list beyond |
returnName |
logical: FALSE to Default = |
1. If is.numeric(name) In <- (1 <= name <= length(object))
2. else In <- if(name %in% names(object))
3. El <- if(In) object[[name]] else default
4. warn.NULL?
5. if(returnName) return(as.character(El)) else return(eval(El, envir=object))
an object of the form of object[[name]]; if object does
not have an element or slot name, return default.
Spencer Graves with help from Marc Schwartz and Hadley Wickham
getElement, which also can return slots from S4 objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | ##
## 1. name in object, return
##
e1 <- getElement2(list(ab=1), 'ab', 2) # 1
# check
all.equal(e1, 1)
##
## 2. name not in object, return default
##
eNA <- getElement2(list(), 'ab') # default default = NA
# check
all.equal(eNA, NA)
e0 <- getElement2(list(), 'ab', 2) # name not in object
all.equal(e0, 2)
e2 <- getElement2(list(ab=1), 'a', 2) # partial matching not used
all.equal(e2, 2)
##
## 3. name NULL in object, return default
##
ed <- getElement2(list(a=NULL), 'a',2) # 2 with a warning
all.equal(ed, 2)
e. <- getElement2(list(a=NULL), 'a', 2, warn.NULL=FALSE) # NULL
all.equal(e., NULL)
eNULL <- getElement2(list(a=NULL), 'a', NULL) # NULL
all.equal(eNULL, NULL)
##
## 4. Language: find, eval, return
##
Qte <- quote(plot(1:4, y=x, col=c2))
if(require(pryr)){
Qt <- pryr::standardise_call(Qte) # add the name 'x'
fn <- getElement2(Qt)
eQuote <- getElement2(Qt, 'y')
Col2 <- getElement2(Qt, 'col', envir=list(c2=2))
# check
all.equal(fn, 'plot')
all.equal(eQuote, 1:4)
all.equal(Col2, 2)
}
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.