You can use the following basic syntax to find the max value in each row of a data frame in R:
df$max <- apply(df, 1, max, na.rm=TRUE)
This particular syntax creates a new column called max that contains the max value in each row of the data frame.
The following example shows how to use this syntax in practice.
Example: Find the Max Value in Each Row in R
Suppose we have the following data frame in R:
#create data frame
df <- data.frame(points=c(4, NA, 10, 2, 15, NA, 7, 22),
rebounds=c(NA, 3, 9, 7, 6, 8, 14, 10),
assists=c(10, 9, 4, 4, 3, 7, 10, 11))
#view data frame
df
points rebounds assists
1 4 NA 10
2 NA 3 9
3 10 9 4
4 2 7 4
5 15 6 3
6 NA 8 7
7 7 14 10
8 22 10 11
We can use the following syntax to create a new column called max that contains the max value in each row:
#add new column that contains max value in each row df$max <- apply(df, 1, max, na.rm=TRUE) #view updated data frame df points rebounds assists max 1 4 NA 10 10 2 NA 3 9 9 3 10 9 4 10 4 2 7 4 7 5 15 6 3 15 6 NA 8 7 8 7 7 14 10 14 8 22 10 11 22
The new column called max contains the max value in each row.
Note: If you don’t include na.rm=TRUE within the apply() function, then NA values will be returned if they exist anywhere in the row.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Calculate the Mean by Group in R
How to Average Across Columns in R
How to Sum Specific Columns in R