R Error in strsplit : non-character argument (Example)

 

In this tutorial, I’ll show how to handle the “Error in strsplit : non-character argument” in the R programming language.

Table of contents:

It’s time to dive into the examples…

 

Creating Example Data

The following data will be used as basement for this R programming tutorial:

x <- 123431211215                         # Create example data
x                                         # Print example data
# [1] 123431211215

As you can see based on the previous RStudio console output, our example data contains a single numeric value.

Let’s try to split these data!

 

Example 1: Reproduce the Error in strsplit : non-character argument

This section illustrates how to replicate the “Error in strsplit : non-character argument”.

Let’s assume that we want to split our number at each position where our data has the value 2.

Then, we might try to use the strsplit function as shown below:

strsplit(x, split = "2")                  # Try to apply strsplit function
# Error in strsplit(x, split = "2") : non-character argument

Unfortunately, the RStudio console returns the “Error in strsplit : non-character argument”.

The reason for this is that we have applied the strsplit function to a numeric data object, even though the strsplit function only takes character strings as input.

Let’s have at look what the help documentation of the strsplit function. The strsplit function takes a…

character vector, each element of which is to be split. Other inputs, including a factor, will give an error.

So how can we handle this problem in R?

 

Example 2: Fix the Error in strsplit : non-character argument

The syntax below explains how to avoid the “Error in strsplit : non-character argument”.

For this, we simply have to convert our numeric value to the character class using the as.character function:

strsplit(as.character(x), split = "2")    # Convert input to character
# [[1]]
# [1] "1"    "3431" "11"   "15"

Looks good!

 

Video & Further Resources

Have a look at the following video of my YouTube channel. In the video, I’m explaining the topics of this post in R:

 

The YouTube video will be added soon.

 

Also, you might have a look at the related tutorials of this homepage:

 

At this point you should know how to deal with the “Error in strsplit : non-character argument” in the R programming language. Please let me know in the comments, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top