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. Let’s see how to calculate Maximum value in R with an example.
- Maximum of the single column in R – max() function
- Maximum values of multiple columns in R
- Maximum values of Multiple columns in R using dplyr
- Find Maximum value of the column by column name
- Find Maximum value of the column by column position
- Get Row wise maximum in R
Let’s first create the dataframe.
### Create Data Frame df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), Grade_score=c(4,6,2,9,5,7,8), Mathematics1_score=c(45,78,44,89,66,49,72), Science_score=c(56,52,45,88,33,90,47)) df1
So the resultant dataframe will be
Get Maximum value of the column in R: Mean of the column by column name
Method 1: Get Maximum value of the column by column name
# Get Maximum value of the column by column name max(df1$Mathematics1_score)
Result:
Get Maximum value of the column in R: Mean of the column by column position
Method 2:Get Maximum value of the column by column position
# Get Maximum value of the column by column position max(df1[,3])
Result:
Get Maximum of multiple columns R using colMaxs() : Method 1
ColMaxs() Function along with sapply() is used to get the maximum value of multiple columns. Dataframe is passed as an argument to ColMaxs() Function. Maximum of numeric columns of the dataframe is calculated. ColMaxs() Function is applied only to matrix, so the dataframe is converted to matrix using as.matrix() function.
# Get Max of the multiple columns colMaxs(as.matrix(df1[sapply(df1, is.numeric)]))
Maximum of numeric columns of the dataframe will be
Get Max of multiple columns in R using Dplyr : Method 2
summarise_if() Function along with is.numeric is used to get the max of the multiple column . With the help of summarise_if() Function, Max of numeric columns of the dataframe is calculated.
# Get Max of the multiple columns using dplyr library(dplyr) df1 %>% summarise_if(is.numeric, max)
Max of numeric columns of the dataframe will be
Get Row wise max in R
Let’s calculate the row wise maximum of mathematics1_score and science_score as shown below
# Get Row wise max in R df1$Max_score = rowMaxs(as.matrix((df1[,c(3,4)]) )) df1
so the resultant dataframe with row wise max calculated will be
Other Related Topics: