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
  • 36,904
  • 9
  • 50
  • 61
mowglis_diaper
  • 419
  • 1
  • 9
  • 15

3 Answers3

3

Simple:

as.data.frame(lapply(df, max))
#   row1 row2 row3                                                               
# 1    2    3    4   
Ernest A
  • 7,196
  • 8
  • 33
  • 39
3

With data.table:

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

Result:

   row1 row2 row3
1:    2    3    4
acylam
  • 17,372
  • 5
  • 30
  • 43
2

Using dplyr

df %>% dplyr::summarise_all(max)

#   row1 row2 row3
# 1    2    3    4
Kevin Arseneau
  • 5,966
  • 1
  • 20
  • 40