Add a variable to a data frame containing max value of each row

You can use apply. For instance:

df[, "max"] <- apply(df[, 2:26], 1, max)

Here’s a basic example:

> df <- data.frame(a=1:50, b=rnorm(50), c=rpois(50, 10))
> df$max <- apply(df, 1, max)
> head(df, 2)
  a          b  c max
1 1  1.3527115  9   9
2 2 -0.6469987 20  20
> tail(df, 2)
    a          b  c max
49 49 -1.4796887 10  49
50 50  0.1600679 13  50

Leave a Comment