min for each row with dataframe in R

Rob picture Rob · Jan 8, 2016 · Viewed 42.8k times · Source

I'm try to do a simple minimum across multiple columns in a data frame but the min function automatically returns the min across the whole of each column rather than for each row separately. I'm sure I'm missing something really simple here? Any ideas much appreciated.

x<-c(1,2,7)
y<-c(1,5,4)
minIwant <- c(1,2,4)
df <- data.frame(x,y,minIwant)
df$minIget <- min(df$x,df$y)
df
  x y minIwant minIget
1 1 1        1       1
2 2 5        2       1
3 7 4        4       1

Answer

nico picture nico · Jan 8, 2016

You can use apply to go through each row

apply(df, 1, FUN=min)

Where 1 means to apply FUN to each row of df, 2 would mean to apply FUN to columns.