Calculate max/min (across columns) for every row in R
Post date: Apr 9, 2014 9:30:38 PM
Use function "apply" to do so, and it works for both row or column.
> df <- data.frame("a"=c(1,NA,3,4,5), "b"=c(1,NA,NA,5,6), "c"=c(1,NA,5,6,2)) > df a b c 1 1 1 1 2 NA NA NA 3 3 NA 5 4 4 5 6 5 5 6 2
# --- first we will apply this for each row --- > apply(X=df, MARGIN=1, FUN=max) [1] 1 NA NA 6 6 > apply(X=df, MARGIN=1, FUN=max, na.rm=T) [1] 1 -Inf 5 6 6 Warning message: In FUN(newX[, i], ...) : no non-missing arguments to max; returning -Inf
# --- We can apply this for each column --- > apply(X=df, MARGIN=2, FUN=max, na.rm=T) a b c 5 6 6
Created by Pretty R at inside-R.org