Kamyar Parastesh Kamyar Parastesh - 2 years ago 134
R Question

R: How to access a function in the list?

Assume i have a

as below:

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

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

function (x) .Primitive("sin")

what if i want to pass an element to it?

For instance i want to get

I have tried the

Error: attempt to apply non-function

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download