This does not answer your question exactly, but I found it while trying to figure out a similar question so I'll show you something.
Say you have a function which you want to apply to each element of a matrix which requires just one part.
mydouble <- function(x) {
return(x+x)
}
And say you have a matrix X,
> x=c(1,-2,-3,4)
> X=matrix(x,2,2)
> X
[,1] [,2]
[1,] 1 -3
[2,] -2 4
then you do this:
res=mydouble(X)
Then it will do an element-wise double of each value.
However, if you do logic in the function like below you will get a warning that it is not parameterized and not behave as you expect.
myabs <- function(x) {
if (x<0) {
return (-x)
} else {
return (x)
}
}
> myabs(X)
[,1] [,2]
[1,] 1 -3
[2,] -2 4
Warning message:
In if (x < 0) { :
the condition has length > 1 and only the first element will be used
But if you use the apply() function you can use it.
For example:
> apply(X,c(1,2),myabs)
[,1] [,2]
[1,] 1 3
[2,] 2 4
So that is great, right? Well, it breaks down if you have a function with two or more parms. Say for example you have this:
mymath <- function(x,y) {
if(x<0) {
return(-x*y)
} else {
return(x*y)
}
}
In this case, you use the apply() function. However, it will lose the matrix but the results are calculated correctly. They can be reformed if you are so inclined.
> mapply(mymath,X,X)
[1] 1 -4 -9 16
> mapply(mymath,X,2)
[1] 2 4 6 8
> matrix(mapply(mymath,X,2),c(2,2))
[,1] [,2]
[1,] 2 6
[2,] 4 8
apply()
family of functions? The MARGIN parameter accepts values for rows, columns, and rows & columns. Not to mention that quite a few R functions are vectorized and can avoid this type of programming. – Chasef()
? As far as I can tell, any vectorized function will work on a matrix as it is just a vector with a dim attribute. You don't need to break it down into row and columns indices. At the moment there is an amount of ambiguity in your Q; it seems like you want a general solution but proscribe that it should b based on indices, which is sub-optimal. – Gavin Simpsonf()
be written such that all you really need ism[] <- f(m)
? I'll add an example... – Gavin Simpson