Jeff
Jeff

Reputation: 8431

How to access a function in the list?

Assume i have a list as below:

mylist<-list( c(12,3,12,5),"Hello R",sin  )

so, the third element of my mylist is a sin(x) function:

mylist[3]
[[1]]
function (x)  .Primitive("sin")

what if i want to pass an element to it?

For instance i want to get sin(90)

I have tried the mylist[3](90):

mylist[3](90)
Error: attempt to apply non-function

Upvotes: 1

Views: 181

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70653

You are very very close. Notice that when you type mylist[3], next to your desired output, you also get [[1]]. This means that this is a list with element 1. You can see this if you do

> str(mylist[3])
List of 1
 $ :function (x)

To subset the very element of the list (and not just the third list element), you should use double bracket.

> mylist[[3]](90)
[1] 0.8939967

Here is a nice representation of how to work with lists in R.

Alternatively, you could name your elements and access them that way.

> mylist <- list(a = c(12,3,12,5), b = "Hello R", allmysins = sin)
> mylist$allmysins(90)
[1] 0.8939967

Upvotes: 4

Related Questions