Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a function call to pmax from the columns of a matrix

Tags:

r

matrix

I want to use pmax to compute the row-wise maximium of a matrix A:

A = matrix(sample(1:20),10,2)
pmax(A[,1],A[,2])

this works fine. But the problem is that I don't know the size of A, so the call to pmax should be able to split the matrix by columns and supply each column as an argument. how to do that? For example, I may in the next instance have

A = matrix(sample(1:20),5,4)

But I don't want to have to rewrite by hand every time to

pmax(A[,1],A[,2],A[,3],A[,4])

in fact, I can't because the size of A is unknown before the start of the program.

like image 627
Florian Oswald Avatar asked May 17 '13 15:05

Florian Oswald


People also ask

How do we call a matrix with same number of rows and columns?

A matrix with the same number of rows and columns is called a square matrix.

Which function is used to add a column or multiple columns to a matrix?

For adding a column to a Matrix in we use cbind() function. To know more about cbind() function simply type ? cbind() or help(cbind) in R.

How do you represent rows and columns in a matrix?

A matrix is denoted by [aij]mxn, where i and j represent the position of elements in the matrix, row-wise and column-wise, m is the number of rows and n is the number of columns.


2 Answers

You can use do.call:

do.call(pmax, as.data.frame(A))
like image 136
Matthew Plourde Avatar answered Sep 22 '22 13:09

Matthew Plourde


Just use apply with max instead...

apply( A , 1 , max )
# [1]  6 11 20 18 17

pmax(A[,1],A[,2],A[,3],A[,4])
# [1]  6 11 20 18 17
like image 22
Simon O'Hanlon Avatar answered Sep 22 '22 13:09

Simon O'Hanlon