Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element of a list based on its name in a function?

Tags:

r

get

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?

like image 219
user1134616 Avatar asked Dec 05 '25 10:12

user1134616


1 Answers

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
like image 58
Andreas Avatar answered Dec 07 '25 01:12

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!