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:
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
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
NOTE: nchar() requires a character column to calculate string length. Otherwise it will return error.