Kamyar Parastesh - 5 months ago 22

R Question

Assume i have a

`list`

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

so, the

`mylist`

`mylist[3]`

[[1]]

function (x) .Primitive("sin")

For instance i want to get

`sin(90)`

I have tried the

`mylist[3](90)`

`mylist[3](90)`

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
```