How to Fix: error in strsplit(unitspec, ” “) : non-character argument

One error you may encounter in R is:

Error in strsplit(df$my_column, split = "1") : non-character argument 

This error usually occurs when you attempt to use the strsplit() function in R to split up a string, yet the object you’re working with is not a string.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C'),
                 points=c(91910, 14015, 120215))

#view data frame

  team points
1    A  91910
2    B  14015
3    C 120215

Now suppose we attempt to use the strsplit() function to split the values in the “points” column based on where the number 1 occurs:

#attempt to split values in points column
strsplit(df$points, split="1")

Error in strsplit(df$points, split = "1") : non-character argument

We receive an error because the variable “points” is not a character.

We can confirm this by checking the class of this variable:

#display class of "points" variable

[1] "numeric"

We can see that this variable has a class of numeric.

How to Fix the Error

The way to fix this error is to use as.character() to convert the “points” variable to a character before attempting to use the strsplit() function:

#split values in points column based on where 1 appears
strsplit(as.character(df$points), split="1")

[1] "9" "9" "0"

[1] ""   "40" "5" 

[1] ""    "202" "5"  

This time we’re able to successfully split each value in the “points” column because we first used the as.character() function to convert “points” to a character.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: more columns than column names
How to Fix in R: replacement has X rows, data has Y

Leave a Reply

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