Select Page

How to Solve R Error in strsplit : non-character argument

by | Programming, R, Tips

This error occurs when you try to split a non-character vector using the strsplit() function. The strsplit() function only takes character vectors as input. You can solve this error by non-character value to the character class using the as.character() function, then passing the value to the strsplit() function. For example,

x <- 111111011111

x_ch <- as.character(x)

strsplit(x_ch, split="0")

This tutorial will go through how to solve the error with code examples.

Table of contents


Let’s look at an example to reproduce the error. First, we will define a numeric vector:

x <- 111111011111

Then, we will try to split the vector based on the value "0".

split_str <- strsplit(x, split="0")

Let’s run the code to see what happens:

Error in strsplit(x, split = "0") : non-character argument

The error occurs because the strsplit() function splits the elements of character vectors only, yet we passed a numeric vector instead.


We can solve the error by casting the numeric vector to a character vector using the as.character() function. We can check the class of a vector using the class() function as follows:

x <- 111111011111
x_ch <- as.character(x)
[1] "numeric"
[1] "character"

Once we have the character vector, we can split it using the strsplit() function as follows:

split_str <- strsplit(x_ch, split="0")

Let’s run the code to get the list containing the split elements.

[1] "111111" "11111" 
[1] "list"


Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!