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

Example

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.

Solution

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)
class(x)
class(x_ch)
[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")
class(split_str)

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

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

Summary

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!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee