How to find the length of the largest string in an R data frame column?


The length of the largest string can be found with the help of max function combined with nchar function. For this purpose, we first need to access the appropriate column that contains string values. Suppose, we have a data frame called df that contains a string column defined as CHAR then the length of the largest string will be found by using the command max(nchar(df$CHAR)).

Consider the below data frame −

Example

 Live Demo

x<-sample(c("India","China","UK","USA","Japan","Sudan"),20,replace=TRUE)
df1<-data.frame(x)
df1

Output

    x
1  USA
2  USA
3  Sudan
4  India
5  Japan
6  Japan
7  Sudan
8  India
9  India
10 Japan
11 Sudan
12 Japan
13 China
14 Sudan
15 UK
16 China
17 UK
18 Japan
19 India
20 USA

Finding the largest string in column x of df1 −

max(nchar(df1$x))

[1] 5

Example

 Live Demo

y<-sample(c("Spring","Summer","Winter","Rainy"),20,replace=TRUE)
df2<-data.frame(y)
df2

Output

      y
1  Spring
2  Spring
3  Winter
4  Winter
5  Summer
6  Rainy
7  Summer
8  Spring
9  Spring
10 Winter
11 Rainy
12 Rainy
13 Rainy
14 Summer
15 Winter
16 Summer
17 Rainy
18 Winter
19 Winter
20 Spring

Finding the largest string in column y of df2 −

max(nchar(df2$y))

[1] 6

Example

 Live Demo

z<-sample(c("Digital Marketing","Data Science","Leadership","IT"),20,replace=TRUE)
df3<-data.frame(z)
df3

Output

    z
1  Data Science
2  IT
3  Leadership
4  Data Science
5  Digital Marketing
6  Digital Marketing
7  Data Science
8  Data Science
9  IT
10 Data Science
11 Leadership
12 Digital Marketing
13 Data Science
14 Digital Marketing
15 Leadership
16 Digital Marketing
17 IT
18 Data Science
19 Leadership
20 Digital Marketing

Finding the largest string in column z of df3 −

max(nchar(df3$z))

[1] 17

Updated on: 06-Feb-2021

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements