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?