Select column with the longest string in R

df$winner <- apply(df,1, function(x) x[which.max(nchar(x))])

    V1  V2  V3 winner
1.   A AAA   B    AAA
2. BBB   B  CC    BBB
3.   C  BB CCC    CCC

In case of of ties winner will be based on first apperance:

df$WINNER <- apply(df, 1, function(row) row[which.max(nchar(row))])

You can use c_across(). What you put in there will control which columns are selected.


df %>% 
  rowwise() %>% 
  mutate(WINNER = c_across(starts_with("V"))[which.max(nchar(c_across(starts_with("V"))))])

It can be a bit more compact if you want all columns.

df %>% 
  rowwise() %>% 
  mutate(WINNER = c_across()[which.max(nchar(c_across()))])