Finding the maximum value for each row among 3 columns in R
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?
Solution 1:
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
Solution 2:
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.