[R] How to apply a function on each column of a matrix
(Ted Harding)
Ted.Harding at manchester.ac.uk
Sun Jan 24 01:49:15 CET 2010
On 24-Jan-10 00:27:37, Jim Lemon wrote:
> On 01/24/2010 11:11 AM, anna wrote:
>>
>> Here is the last code that I wrote but it would give me the
>> same problem:
>> I have the matrix mat with n columns mat.1, mat.2 ...mat.n
>>
>> #To be able to use lapply I convert it to a data.frame:
>> mat<- data.frame(mat)
>>
>> lapply(mat, function, argument of function)
>>
>> It works but I still get for all elements the function applied
>> for the last element. The elements of my results are all the
>> same I don't understand I did exactly as shown on this website:
>> http://www.ats.ucla.edu/stat/r/library/advanced_function_r.htm#lapply
>
> Hi anna,
> If you could post your matrix "mat" (or something else that
> produces the problem you describe if "mat" is private or too big)
> and the commands you used, someone will probably figure out what
> is going wrong.
>
> Jim
I agree with Jim's comments. It may help to formulate your reply
to considet the following simple case of applying a function "on
each column of a matrix":
X2 <- function(x){ x^2 }
M <- matrix(c(1,2,3,4,5,6,7,8,9),nrow=3)
M
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
X2 <- function(x){ x^2 }
apply(M,2,X2)
# [,1] [,2] [,3]
# [1,] 1 16 49
# [2,] 4 25 64
# [3,] 9 36 81
SX2 <- function(x){ sum(x^2) }
apply(M,2,SX2)
# [1] 14 77 194
Not ythe use of apply(), not lapply(); also that the result is
not a matrix (with 1 row) but a vector (dimensionless):
dim(apply(M,2,SX2))
# NULL
If you want the result to be a 1-row vector, then you need to
force this explicitly:
N <- apply(M,2,SX2)
# dim(N)<-c(1,3)
N
# [,1] [,2] [,3]
# [1,] 14 77 194
or (in this case) more simply:
rbind(NULL,apply(M,2,SX2))
# [,1] [,2] [,3]
# [1,] 14 77 194
If that approach does not work with your matrix and your function,
then there must be something special about one or the other!
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 24-Jan-10 Time: 00:49:12
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list