# The nchar R Function | 3 Examples (String, Vector & Error: nchar Requires a Character)

**Basic R Syntax:**

nchar(x) |

nchar(x)

The nchar R function **counts the number of elements** (e.g. letters) of a character object. The basic syntax for nchar in R is illustrated above.

In the following tutorial, I will show you **3 examples** how to apply the nchar command in R. So if you want to know more about nchar, keep reading…

## Example 1: Count nchar of a String in R

Typically, nchar is used for a single string (in R usually called character object). As example, let’s create such a character object in R:

x <- "Hello R User" # Create example character object |

x <- "Hello R User" # Create example character object

To this character object, we can now apply the nchar R function:

nchar(x) # Apply nchar in R # 12 |

nchar(x) # Apply nchar in R # 12

The nchar command returns the value 12 – Our character object has 12 elements.

**Note:** The nchar function also counts spaces, special characters etc.

## Example 2: Use nchar for R Vector

The nchar function can also be applied to a character vector. Let’s create such a vector:

x_vec <- c("Lalala Lololo", "12345", # Create example character vector "1 2 3 4 5", "?=%$§-+????") |

x_vec <- c("Lalala Lololo", "12345", # Create example character vector "1 2 3 4 5", "?=%$§-+????")

Now, let’s apply nchar to this vector:

nchar(x_vec) # Apply nchar to character vector # 13 5 9 11 |

nchar(x_vec) # Apply nchar to character vector # 13 5 9 11

As you can see, nchar returns 4 values – One value for each entry of our input vector. The first entry of the input vector consists of 13 elements; the second entry consists of 5 elements; and so on…

## Example 3: Error in nchar(x) : ‘nchar()’ Requires a Character Vector

There is one error message that R users report regularly:

**Graphic 1: Error – nchar Requires a Character Vector? Don’t Panic!**

But when does this happen? And how to solve this problem? That’s exactly what I’m going to show you now…

First, let’s create another data object – but this time a factor:

x_fac <- as.factor("Fac1") # Create example factor |

x_fac <- as.factor("Fac1") # Create example factor

Now, let’s see what happens when we use the nchar function:

nchar(x_fac) # Apply nchar to factor # Error in nchar(x) : 'nchar()' requires a character vector |

nchar(x_fac) # Apply nchar to factor # Error in nchar(x) : 'nchar()' requires a character vector

You guessed it… The RStudio console returns exactly the previously described error message. So what to do now?

Simply convert your factor to character or numeric, before you apply the nchar function:

nchar(as.character(x_fac)) # Solution # 4 |

nchar(as.character(x_fac)) # Solution # 4

That’s it!

**Note:** Characters in R are often automatically converted to a factor, e.g. when you add them as column to a data frame. If R returns the previous error message, check carefully if all your data has the format that it should have.

## Video Explanation: The R nchar Function

Do you need more explanations and examples? Have a look at the following video of the YouTube channel Dragonfly Statistics.

## Further Reading

- The ncol Function in R
- The nrow Function in R
- The length Function in R
- How to Convert a Factor to Numeric
- The R Programming Language

### Subscribe to my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R