Open In App

How to find maximum string length by column in R DataFrame ?

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to find maximum string length by column in R Programming Language. 

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. The nchar() and the max() function are base functions of the R programming language, so there is no need to import any package.

nchar() function takes a character vector as an argument and returns a vector whose elements contain the sizes of the corresponding elements of x

Syntax:

nchar(x, type = “chars”, allowNA = FALSE, keepNA = NA)

Parameter:

  • x: character vector or a vector to be coerced to a character vector. Giving a factor is an error.
  • type:character string: partial matching to one of c(“bytes”, “chars”, “width”). See ‘Details’.
  • allowNA: logical, should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?
  • keepNA:logical: should NA be returned wherever x is NA?

max() function finds the maximum value among the data provided.

Syntax:

MAX(vector, rank = 1, value = FALSE, rank.adjust = TRUE, forceChoice = FALSE)

Parameter:

  • vector: Vector in which maximum/minimum element needs to be identified
  • rank:value(s) or rank(s) of maximum values.
  • value:  Should value or rank be returned?
  • rank.adjust: If the maximum value of a range of ranks exceeds vector length, should this be adjusted?
  • forceChoice: In the case of ties, should all results be returned or only one?

Example1:

R




gfg_data <- data.frame(x = c("geeks", "for", "geeks"), 
                       y = c("I", "Love", "Coding"),
                       z=c("R", "programming ", "language"))
 
max(nchar(gfg_data$y)) 


Output:

[1] 6

Example 2:

R




gfg_data <- data.frame(x = c("geeks", "for", "geeks"), 
                       y = c("I", "Love", "Coding"),
                       z=c("R", "programming ", "language"))
 
max(nchar(gfg_data$z)) 


Output:

[1] 12


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads