Get String length of the column in R dataframe

To get the string length of the column in R we use either str_length() function or nchar() function. Let’s see how to

  • Get string length of the column in R with examples

Let’s first create the dataframe

df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), 
                 Mathematics_score=c(45,78,44,89,66,NaN,NaN))
df1 

So the resultant dataframe will be

Get string length of the column in R 1

 

Get String Length of the column in R:

Method 1 (using stringr package) :

Get String length of the column in R using str_length function of “stringr” package.

library(stringr)
df1$Name_length1 = str_length(df1$Name) 
df1

so the resultant dataframe is

Get string length of the column in R 2

 

Method 2 (nchar() function):

Get String length of the column in R using nchar() function. nchar() function requires a character column to calculate string length.

df1$Name_length = nchar(as.character(df1$Name))
df1

Result will be

Get string length of the column in R 3

NOTE: nchar() requires a character column to calculate string length. Otherwise it will return error.

                                                                                                       

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts