Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select column with the longest string in R

I have this type of dataset

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

And I would like to select the longest string from DF and put it into the new column WINNER like this:

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

I have tried

mutate( WINNER = select(which.max (c(nchar(V1), nchar(V2), nchar(V3))) 

but it works only for numeric values. I would prefer dplyr solution.

like image 305
onhalu Avatar asked Jun 26 '20 12:06

onhalu


People also ask

How to find the longest string in a column R?

To find the maximum string length by column in the given dataframe, first, nchar() function is called to get the length of all the string present in the particular column of the dataframe, and then the max() function must be called to get the maximum value of the length of the string generated by the nchar() function.

How do I find the length of a column in a Dataframe in R?

Hi, Use nrow() and ncol() to determine the number of rows and columns of a data frame.

How do you find the longest element in a list?

To get every largest element, in linear time, you have to do m=max(map(len,xs)); [x for x in xs if len(x) == m] .


1 Answers

df$winner <- 
  Reduce(function(x, y) ifelse(nchar(y) > nchar(x), y, x), df) 

df
#     V1  V2  V3 winner
# 1:   A AAA   B    AAA
# 2: BBB   B  CC    BBB
# 3:   C  BB CCC    CCC
like image 83
IceCreamToucan Avatar answered Oct 05 '22 06:10

IceCreamToucan