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.

## 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!

##### Suf
Research Scientist at | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!