Consider this list:
l <- list(a=1:10,b=1:10,c=rep(0,10),d=11:20)
Then consider this example code (representative of the real larger code). It simply selects the right element in the list based on name.
Parameters:
object:a list with at maximum four elements (i.e, sometimes less than four). The elements are always called a,b,c and d but do not always appear in the same order in the list.
x: name of element to select (i.e, a,b,c or d)
slct <- function(object,x) {
if (x=="a") {
object$a
} else if (x=="b") {
object$b
} else if (x=="c") {
object$c
} else if (x=="d") {
object$d
}
}
slct(l,"d")
That approach becomes impractible when you have not a mere 4 elements, but hundreds. Moreover I cannot select based on a number (e.g., object[[1]]) because the elements don't come in the same order each time. So how can I make the above code shorter?
I was thinking about the macro approach in SAS, but of course this doesn't work in R.
slct <- function(object,x) {
object$x
}
object$a
slct(object=l,x="a")
What do I have to replace object$x with to make it work but with less code than in the above code?
Simply refer to the element in the list using double brackets.
l[['a']]
l[['b']]
etc...
Alternatively, you could use regular expressions to build a function!
select <- function(object, x) {
index <- grep(x, names(object))
return(object[[index]])
}
Hope this helps!
You don't even need the grep here. The function above will result in an error if you try for example: select(l, "f") where as modifying the function in this manner will simply return a NULL which you can check with is.null(.):
select <- function(object, x) {
return(object[[x]])
}
select(l, "a")
# [1] 1 2 3 4 5 6 7 8 9 10
select(l, "f")
# NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With