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?
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With