[R] how to apply several math/logic operations on columns/rows of a matrix

David Winsemius dwinsemius at comcast.net
Sat Jul 2 00:03:58 CEST 2011


On Jul 1, 2011, at 1:31 PM, Marc Jekel wrote:

> Dear R-Fans,
>
> The more I work with matrices (e.g., data.frames) the more I think  
> it would be helpful to have functions to apply (several!)  
> mathematical and/or logical operators column- or row-wise in a matrix.
>
> I know the function apply() and all its derivates (e.g., lapply)   
> but I think this does not help for solving  (e.g.) the following task:
>
> assume there is a 3x3 matrix:
>
> 1    2    4
> 4    5    3
> 1    3    4
>
> How do I find - for each column separately - the position of the  
> column's minimum without using loop commands, i.e.:

?which.min  # should have been linked from the help(which) page. ...  
Yep, it is.

 > mtx <- matrix(scan(textConnection("1    2    4
+ 4    5    3
+ 1    3    4")), 3, byrow=TRUE)
Read 9 items
 > mtx
      [,1] [,2] [,3]
[1,]    1    2    4
[2,]    4    5    3
[3,]    1    3    4
 > apply(mtx, 2, which.min)
[1] 1 1 2



>
> I could extract each column in a loop and use something like:
>
> for (loopColumn in 1 : 3){
>
> extractedColumnVector  = myMatrix[, loopColumn]
>
> position = which(extractedColumnVector == min  
> (extractedColumnVector ) )
>
> print(position)
> }
>
> I think that there should be something simpler out there to handle  
> these kinds of tasks (maybe there is and I just don't know but I  
> checked several R books and could not find a command to do this).
>
> It would be great to have a function in which it is possible to  
> define a sequence of commands that can be applied column/row-wise.
>
> Thanks for a hint,
>
> Marc
>
> -- 
> Dipl.-Psych. Marc Jekel
>
> MPI for Research on Collective Goods
> Kurt-Schumacher-Str. 10
> D-53113 Bonn
> Germany
>
> email: jekel at coll.mpg.de
> phone: ++49 (0) 228 91416-852
>
> http://www.coll.mpg.de/team/page/marc_jekel-0
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list