# nchar in R: Get size of the elements in the R object

## What does nchar() do in R?

The nchar() function in R can help you get the size of all elements in the R object. You can use this function with the vector, the array, and the data frame…

With this function, you can customize it to count the length of the character string based on one of the types: bytes, chars, or widths. Let’s take a look at the syntax of the nchar() function in R.

Syntax:

nchar(x, type, allowNA, keepNA)

Parameters:

• x: The R object whose value is the String.
• type: The default is chars. One of the types: chars, bytes, or widths.
• allowNA: The default is FALSE. If TRUE, the NA value is returned for invalid multibyte strings.
• keepNA: The default is NA. Keep the NA value or replace it with 2.

After learning what the nchar in R is, and the syntax of this function, you will learn how to use it in the next title below.

## How to use the nchar function in R?

The nchar() function in R can help you get the size of the elements in the R object. It can get the length of the strings, even the number. Let’s take a look at some examples below.

### Use the nchar function with the vector

You can use the nchar() function to get the size of all elements in the vector.

Look at the example below.

# Create a vector.
vec <- c(10, 20, 30, 'LearnShareIT', 'crvt4722', NA)

# Get the size of elements in the vector.
nchar(vec)

Output

[1] 2 2 2 12 8 NA

### Handle the NA value with nchar function

You can handle the NA value by the nchar function. You can simply assign the parameter named ‘keepNA’ as FALSE. This function will convert the NA value to the String as ‘NA’, so the size of the NA value is converted to 2.

Look at the example below.

# Create a vector.
vec <- c(10, 20, 30, 'LearnShareIT', 'crvt4722', NA)

# Get the size of elements in the vector.
nchar(vec, keepNA = FALSE)

Output

[1] 2 2 2 12 8 2

### Use the nchar function with the data frame

You can get the size of elements in the column by the nchar() function.

Look at the example below.

# Create a data frame.
df <- data.frame( name = c ('Ronaldo', 'Bruno', 'Leao', 'Dalot', 'Vitinha'),
country = c('Portugal', 'Portugal' ,'Portugal', 'Portugal', 'Portugal') )

# Get the length of elements in the 'name' column.
nchar(df\$name)

Output

[1] 7 5 4 5 7

## Summary

You have learned the usage, the syntax, and how to use the nchar in R. By this function, you can get the size of elements in the R object. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested:

Posted in R