If you want to calculate min or max for a range of columns in each row of the data frame in R, then here is how to do that easily.
Here is my data frame.
df <- data.frame( agent = as.character(c("David", "John", "Paul", "Kate", "Thomas", "Alma", "Grace")), v1 = as.numeric(c(701.82, 698.73, NA, NA, 698.71, 698.59, 690.83)), v2 = as.numeric(c(697.87, NA, 76.44, 95.53, 629.38, 486.48, 328.51)), v3 = as.numeric(c(283.02, 783.89, NA, NA, 902.52, 990.53, 812.63)), v4 = as.numeric(c(201.40, 215.42, 57.47, 301.33, NA, NA, NA)) ) # agent v1 v2 v3 v4 min #1 David 701.82 697.87 283.02 201.40 201.40 #2 John 698.73 NA 783.89 215.42 215.42 #3 Paul NA 76.44 NA 57.47 57.47 #4 Kate NA 95.53 NA 301.33 95.53 #5 Thomas 698.71 629.38 902.52 NA 629.38 #6 Alma 698.59 486.48 990.53 NA 486.48 #7 Grace 690.83 328.51 812.63 NA 328.51
I will calculate a minimum value for each row in specific columns. Let’s say from the second column to the fifth. As you can see, there are also missing values. There is an easy method how to replace them with zeros. In this case, it is not what I need to execute minimum value calculation properly.
Min, max, mean, or sum functions in R containsĀ the na.rm parameter that allows ignoring NA values during the calculation.
One of the ways how to execute calculations in each row is by using the function apply.
Min or max calculation for each row in R executed as follows. Na.rm parameter allows calculating that by ignoring NAs.
df$min <- apply(df[2:5], MARGIN = 1, FUN = min, na.rm = T) # agent v1 v2 v3 v4 min #1 David 701.82 697.87 283.02 201.40 201.40 #2 John 698.73 NA 783.89 215.42 215.42 #3 Paul NA 76.44 NA 57.47 57.47 #4 Kate NA 95.53 NA 301.33 95.53 #5 Thomas 698.71 629.38 902.52 NA 629.38 #6 Alma 698.59 486.48 990.53 NA 486.48 #7 Grace 690.83 328.51 812.63 NA 328.51
There is a margin parameter that allows doing the calculations by rows or columns. For a matrix 1 indicates rows, 2 indicates columns.
Check outĀ my favorite RStudio tips and tricks. For example, how to quickly view a data frame from R script.
Leave a Reply