Finding the length of string in R programming – nchar() method

nchar() method in detail

The nchar() function in R is used to determine the number of characters in a string object.

Syntax:

nchar(string)

Return Value:

The function returns the length (number of characters) present in the given string.

Example 1: Finding the Length of a String

In this example, we will calculate the length of a string using the nchar() function.

# R program to determine the length of a string

# Define a string
text <- "Hello R Programming"

# Use nchar() function
length_result <- nchar(text)

print(length_result)

Output:

[1] 20

Example 2: Using nchar() with Character Vectors

This example demonstrates how to apply nchar() to a vector containing different types of elements.

# R program to get the length of character vectors

# Defining a character vector
vec <- c('code', '7', 'world', 99)

# Displaying the type of vector
typeof(vec)

# Applying nchar() function
nchar(vec)

Output:

'character'
4 1 5 2

Example 3: Handling NA Values in nchar()

The nchar() function provides an optional argument keepNA, which helps when dealing with NA values.

# R program to handle NA values using nchar()

# Defining a vector with NULL and NA values
vec <- c(NULL, '3', 'data', NA)

# Applying nchar() with keepNA = FALSE
nchar(vec, keepNA = FALSE)

Output:

1 4 2

Here, NULL returns nothing, and NA is counted as 2 when keepNA = FALSE.

If we set keepNA = TRUE, the output will be:

# Applying nchar() with keepNA = TRUE
vec <- c('', NULL, 'data', NA)

nchar(vec, keepNA = TRUE)

Output:

0 4 <NA>

This means that an empty string returns 0, and NA is explicitly shown as <NA> when keepNA = TRUE.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *