One error you may encounter in R is:
Error in sum(x) : invalid 'type' (character) of argument
This error occurs when you attempt to perform some mathematical operation (like taking the sum, mean, count, etc.) on a character vector.
This tutorial shares how to resolve this error in practice.
How to Reproduce the Error
Suppose we create the following data frame in R:
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'),
points=c(10, 12, 15, 20, 26, 25),
rebounds=c(7, 8, 8, 14, 10, 12))
#view data frame
df
team points rebounds
1 A 10 7
2 A 12 8
3 A 15 8
4 B 20 14
5 B 26 10
6 B 25 12
Now suppose we attempt to calculate the sum of the ‘team’ column:
#attempt to calculate sum of values in 'team' column
sum(df$team)
Error in sum(df$team) : invalid 'type' (character) of argument
We receive an error because the ‘team’ column is a character column.
We can confirm this by using the class() function:
#view class of 'team' column
class(df$team)
[1] "character"
How to Fix the Error
The way to get around this error is to only use mathematical operations with numeric vectors.
For example, we could use the sum() function to calculate the sum of the values in the ‘points’ column:
#calculate sum of values in 'points' column
sum(df$points)
[1] 108
We could also calculate the sum of the points values, grouped by team:
#calculate sum of points, grouped by team
aggregate(points ~ team, df, sum)
team points
1 A 37
2 B 71
We could even calculate the sum of the points and rebounds values, grouped by team:
#calculate sum of points and sum of rebounds, grouped by team
aggregate(. ~ team, df, sum)
team points rebounds
1 A 37 23
2 B 71 36
Notice that we don’t receive an error with any of these operations because we’re only attempting to calculate the sum for numeric variables.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments