Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the maximum value for each row among 3 columns in R

Tags:

r

max

I need to calculate the maximum value for each row among 3 columns.

A table could be:

x = c(1,2,3,4,5 ) 
y = c(2,3,3,1,1 ) 
z = c(4,3,2,1,1 ) 
df<-data.frame(x,y,z)

I need to get:

    x   y   z   max
1   1   2   4   4
2   2   3   3   3
3   3   3   2   3
4   4   1   1   4
5   5   1   1   5

I tried:

df$max<-max(x, y,z)

But I get:

  x y z max
1 1 2 4   5
2 2 3 3   5
3 3 3 2   5
4 4 1 1   5
5 5 1 1   5

So, how can I do this correctly?

like image 731
GabyLP Avatar asked Sep 19 '14 13:09

GabyLP


People also ask

How do I find the maximum value of each row in R?

max() in R The max() is a built-in R function that finds the maximum value of the vector or data frame. It takes the R object as an input and returns the maximum value out of it. To find the maximum value of vector elements, data frame, and columns, use the max() function.

How do I get the maximum value from multiple columns in R?

Maximum value of a column in R can be calculated by using max() function. Max() Function takes column name as argument and calculates the maximum value of that column. Maximum of single column in R, Maximum of multiple columns in R using dplyr.

How do you find the maximum of multiple columns?

In SQL Server there are several ways to get the MIN or MAX of multiple columns including methods using UNPIVOT, UNION, CASE, etc… However, the simplest method is by using FROM … VALUES i.e. table value constructor. Let's see an example. In this example, there is a table for items with five columns for prices.


2 Answers

Use data.table :)

library(data.table)
x = c(1,2,3,4,5 ) 
y = c(2,3,3,1,1 ) 
z = c(4,3,2,1,1 ) 
dt<-data.table(x,y,z)
dt[, max:=pmax(x,y,z)]
dt
like image 122
nsheff Avatar answered Oct 22 '22 17:10

nsheff


You can use the apply function for this like so:

df$max<-apply(X=df, MARGIN=1, FUN=max)

The MARGIN=1 argument indicated that for every row in X you wish to apply the function in FUN. If you use MARGIN=2 it will be by column or MARGIN=c(1,2) it will be both rows and columns.

like image 36
John Paul Avatar answered Oct 22 '22 15:10

John Paul