1

Say I have something like this

df <- data.frame(row1 = c(1, 2), row2 = c(3, 1), row3 = c(1, 4))

and I want to collapse the columns keeping only the maximum value from each row such that df is a single row containing 2, 3, 4. How can I do this?

lmo
  • 37,904
  • 9
  • 56
  • 69
mowglis_diaper
  • 479
  • 1
  • 9
  • 18

3 Answers3

3

Simple:

as.data.frame(lapply(df, max))
#   row1 row2 row3                                                               
# 1    2    3    4   
Ernest A
  • 7,526
  • 8
  • 34
  • 40
3

With data.table:

library(data.table)
setDT(df)[, lapply(.SD, max)]

Result:

   row1 row2 row3
1:    2    3    4
acylam
  • 18,231
  • 5
  • 36
  • 45
2

Using dplyr

df %>% dplyr::summarise_all(max)

#   row1 row2 row3
# 1    2    3    4
Kevin Arseneau
  • 6,186
  • 1
  • 21
  • 40