Which of the given elements of a data frame is biger in R

Viewed 26

I need to specify which of the given elements is bigger if it's in the first row return "T" and if the second return "F" eg.

    A  B  C  D  E 
1   5  1  3  6  3
2   4  0  1  8  6

I need the output to be in a list like

A "T"
B "T"
C "T"
D "F"
E "F"

I tried something like

if_else(data[1,]>data[2,],'T','F')

But it doesn't seem to work

2 Answers
d <- read.table(header = T, text = "A  B  C  D  E 
1   5  1  3  6  3
2   4  0  1  8  6")

d
#>   A B C D E
#> 1 5 1 3 6 3
#> 2 4 0 1 8 6

sapply(d, \(x) c(T, F)[which.max(x)])
#>     A     B     C     D     E 
#>  TRUE  TRUE  TRUE FALSE FALSE

After R4.1+ apply has gained argument simplify = T so above sapply code can be rewritten to

apply(d, 2,  \(x) c(T, F)[which.max(x)], simplify = T)

OR

do.call(rbind, lapply(d, \(x) c('T', 'F')[which.max(x)]))
  [,1]
A "T" 
B "T" 
C "T" 
D "F" 
E "F"

If using R version prior to 4.1 then replace \(x) with function(x) in above codes

We can use summarise with across

library(dplyr)
d %>% 
    summarise(across(everything(), ~ first(.) == max(.)))
#     A    B    C     D     E
#1 TRUE TRUE TRUE FALSE FALSE

data

d <- structure(list(A = 5:4, B = 1:0, C = c(3L, 1L), D = c(6L, 8L), 
    E = c(3L, 6L)), class = "data.frame", row.names = c("1", 
"2"))
Related