String Length in R

In this tutorial, we will learn how to find string length in R programming.

To find the length of a String in R, use nchar() function. Following is the syntax of nchar function.

</>
Copy
  nchar(x)

where x is of character data type

Example 1 – Find Length of String in R

In this example, we will initialize a variable with a String value and find its length using nchar(string) function.

r_strings_length.R

</>
Copy
# Example R program to find length of string

str = 'Hello World!'

# find length using nchar(c)
length = nchar(str)

print (length)

Output

$ Rscript r_strings_length.R 
[1] 12

Example 2 – Find Length of a Number in R

nchar automatically type casts number to character

r_strings_length.R

</>
Copy
# Example R program to find length of number

num = 523641

# find length using nchar(c)
length = nchar(num)

print (length)

Output

$ Rscript r_strings_length.R 
[1] 6

You may try nchar(c) function for other data types to find the length.

Conclusion

In this R Tutorial, we have learned to use nchar(x) to find the string length or number length in R programming language.