How to Use colMax Function in R
Last Updated :
24 Apr, 2025
As we know in R, while base functions like colMeans and colSums exist to calculate column-wise means and sum in a data frame, there isn't a built-in colMax function for finding the maximum value in each column. So the question arises of how to use the colMax function in R Programming Language.
How to Use the colMax Function in R?
The colMax function is a user-defined function in R that allows users to find the maximum value in each column of a data frame. It is particularly useful for data analysis and exploration tasks. We can use the following syntax to create a colMax function in R.
colMax <- function(data) sapply(data, max, na.rm=TRUE)
where data: The input data frame for which maximum values in each column are to be calculated.
- Once we have created this function, We can then use it to calculate the max value of each column in a data frame in R.
- Given below is an examples showing how to use this function in practice with the following data frame in R.
Calculate Max of All Columns Using colMax
Here we are creating a data frame with sample data representing sales figures for different products over multiple months.
R
#create data frame
df <- data.frame(Product = c("A", "B", "C", "D"),
Jan = c(100, 150, 200, 180),
Feb = c(120, 160, 190, 170),
Mar = c(110, 140, 210, 200))
#view data frame
df
# Define colMax function to find the maximum value in each column
colMax <- function(data) sapply(data, max, na.rm = TRUE)
#view data frame
colMax(df)
Output:
Product Jan Feb Mar
1 A 100 120 110
2 B 150 160 140
3 C 200 190 210
4 D 180 170 200Product Jan Feb Mar
"D" "200" "190" "210"
"D" is the maximum value among the character entries in the "Product" column, and that's why it appears in the output with all the max values of all the columns.
Calculate Max of Specific Columns Using colMax
We can use the following code to calculate the max value for only the points and blocks columns in the data frame.
R
# Define colMax function
colMax <- function(data) sapply(data, max, na.rm = TRUE)
# Create a data frame with sample data
df <- data.frame(
english = c(99, 91, 86, 88, 95),
hindi = c(33, 28, 31, 39, 34),
maths = c(30, 28, 24, 24, 28),
physics = c(1, 4, 11, 0, 2)
)
df
# Calculate maximum value for specific columns
max_values_specific <- colMax(df[, c('english', 'physics')])
# Display maximum values for specific columns
print(max_values_specific)