I am a new to R and am trying to do my homework in it. I have looked many places and I cannot find any instructions as to how to make matricies that contain functions. I need my matrix [A] to have functions like cos(x) and sin(x) in them, and then I need to be able to calculate [A(o degrees)] or [A(30 degrees)] and so on. Is there any way to do this? Thanks for the help
Asked
Active
Viewed 40 times
2
-
3This was the answer I remembered: http://stackoverflow.com/questions/20297711/r-hessian-matrix/20301977#20301977 . I admit that it took four searches because I didn't remember the application of the process correctly. – IRTFM Jan 17 '16 at 20:22
1 Answers
1
This is another method of storing functions in a matrix:
M <- matrix( c( function(x) {cos(x)},
function(x) {sin(x)},
function(x) {tan(x)},
function(x) {asin(x)}),
2,2)
M[1,1]
#-------
[[1]]
function (x)
{
cos(x)
}
To access the contents of each list (after extracting from the matrix object) you need to use [[
, and then it can be used as a function:
M[1,1][[1]](pi)
#[1] -1
Scriven's suggest works as well and is certainly more economical:
> M2 <- matrix( c(cos, sin, tan, asin), 2,2)
> M2
[,1] [,2]
[1,] ? ?
[2,] ? ?
> M2[1,1][[1]](pi)
[1] -1
> class(M2[1,1])
[1] "list"
> class(M2[1,1][[1]])
[1] "function"

IRTFM
- 258,963
- 21
- 364
- 487
-
Couldn't you also use `c(cos, sin, tan, asin)` instead of `function(x)` on all of them? – Rich Scriven Jan 17 '16 at 22:53
-
I did try something like that but perhaps I gave up too soon. When I used them in expression object, they were just names, but now it seems to work fine. – IRTFM Jan 17 '16 at 23:14