How to solve Argument not Numeric or Logical Error in R
Last Updated :
26 Mar, 2024
R is a powerful programming language commonly used for statistical computing, data analysis, and graphical representation. It is highly extensible through packages contributed by a vast community of users. Key features of the R programming language include
However R Programming Language has many advantages, it has some disadvantages also. One common error that the R programming language has is the "argument not numeric or logical" error. This error occurs when a function expects numeric or logical arguments but receives some other data type such as characters or string.
What does an "Argument not Numeric or Logical" error mean?
In R programming language, the "Argument not Numeric or Logical Error" occurs when a function is expecting an input that is of numeric data type or of logical data type, but instead receives something else as arguments which may be a string or character, or other non-numeric/ non-logical argument. This error arises when the r has defined functions that attempt mathematical operations and perform logical comparisons based on the input provided and the input is not in the correct format.
From the below mentioned example you can clearly understand under what situation a user can get this type of error.
R
# Create a data frame with student information
student_data <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(20, 21, 21),
test_score = c("80", "90", "75")
)
# Calculate the average test score
average_score <- mean(student_data$test_score)
print(average_score)
Output:
Warning message:
In mean.default(student_data$test_score) :
argument is not numeric or logical: returning NA
[1] NA
A data frame is created containing information about the marks of students.
- Now through this code we want to calculate the average test score for students.
- The test_score of students are entered as characters instead of numeric value.
- We attempt to calculate the average test score using the `mean()` function.
- However the `mean()` function expected input as numeric data type.
- Here, the input passed is character hence this results into "Argument not Numeric or Logical" error.
How to fix the above code?
The above code can be improved by simply changing the datatype of test_score from character to numeric.
You can convert the character to numeric in R by using the as.numeric() function.
R
# Create a data frame with student information
student_data <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(20, 21, 21),
test_score = c("80", "90", "75")
)
# Convert the character data type to numeric
student_data$test_score <- as.numeric(student_data$test_score)
# Calculate the average test score
average_score <- mean(student_data$test_score)
message <- paste("The Average Score is: ",average_score)
print(message)
Output:
[1] "The Average Score is: 81.6666666666667"
A data frame is created containing information about the marks of students.
- Now through this code we want to calculate the average test score for students.
- The test_score of students are entered as characters instead of numeric value.
- Now, using the as.numeric() function we will convert the character data type value of the test_score to numeric data type.
- The average of the test_score can now be calculated using the mean() function.
Different ways of Dealing with Arguments not Numeric or Logical Error
Method 1: Conversion of Data Type
When the arguments are not in the form which are needed by the function to perform mathematical operations. You can convert the data type of the arguments to numeric or logical to overcome this error.
This conversion from a different data type to numeric can be done using the below functions:
Suppose you have a vector age and you need to calculate average age but the problem arise when the ages are in character format. As the age are in character format we encounter the "Argument not Numeric or Logical" error when we try to calculate the average age using the mean() function. To overcome this error we need to convert the characters into numeric so that the mean() function can be performed on them.
Syntax of as.numeric() function
as.numeric(vector_name)
vector_name represents a vector whose elements we want to make numeric. If the value is as such that it cannot be converted into numeric then the function returns NA.
R
# Vector containing ages as character
age_vector <- c("5", "3", "6", "4", "5")
# Attempt to calculate the average age (will result in an error)
average_age <- mean(age_vector)
Output:
Warning message:
In mean.default(age_vector) :
argument is not numeric or logical: returning NA
To overcome this error the code can be modified as below
R
age_vector <- c("5", "3", "6", "4", "5")
# Convert age_vector to numeric
numeric_age_vector <- as.numeric(age_vector)
# Calculate the average age
average_age <- mean(numeric_age_vector)
message <- paste("The Avergae Age is : ",average_age)
print(message)
Output:
[1] "The Avergae Age is : 4.6"
The code has a vector names`age_vector` which contains ages which is of character data type.
- The code converts these characters to numeric value by using the as.numeric() function.
- Then, to calculate the average age the code uses the mean() function.
- Towards the end of the code the average age is calculated and shown in the output window.
Suppose you have a vector which contains logical values represented as character string "TRUE" or "FALSE" and you want to calculate the proportion of TRUE values.
R
# Vector containing logical values as character strings
count_vector <- c("TRUE", "FALSE", "TRUE", "FALSE","TRUE")
# Attempt to calculate the proportion of TRUE values (will result in an error)
proportion_true <- mean(count_vector)
Output:
Warning message:
In mean.default(count_vector) :
argument is not numeric or logical: returning NA
To overcome this error the code can be modified as below
R
# Vector containing logical values as character strings
count_vector <- c("TRUE", "FALSE", "FALSE","TRUE","TRUE")
# Convert logical_vector to logical
Count1_vector <- as.logical(count_vector)
# Calculate the proportion of TRUE values
proportion_true <- mean(Count1_vector)
message <- paste("The True Count is : ",proportion_true)
print(message)
Output:
[1] "The True Count is : 0.6"
In the above code, the `count_vector` contains string elements "TRUE" and "FALSE".
- Further, a new vector `count1_vector` is introduced into the code which converts the elements of`count_vector` to logical values on which mean operation can be performed.
- The proportion of `TRUE` values in the data can be calculated using the mean() function. As `TRUE` evaluates to 1 and `FALSE` evaluates to 0 the mean of these values will give the proportion of `TRUE` values.
- Towards the end of the code the proportion of `TRUE` value is calculated and shown in the output window.
- The output comes out to be 0.6 , which is equivalent to 60% of the elements are TRUE.
Method 2: Error Handling
To implement error handling mechanisms in code is very efficient way handle any error in code.As, this mechanism gracefully handle situations where unexpected arguments are encountered. The error for `Argument not Numeric or Logical Error` can be removed by using `tryCatch()` block.
R
# Defining a vector
char_vector <- c("11", "20", "3", "geeks")
tryCatch(
{
# converting to numeric data type
numeric_vector <- as.numeric(char_vector)
if (any(is.na(numeric_vector))) {
# warning if any NA found in the vector
cat("Warning: Non-numeric values encountered.\n")
# removing the NA values from the vector
numeric_vector <- numeric_vector[!is.na(numeric_vector)]
}
# performing operation on the vector
sum(numeric_vector)
},
# error function triggred in case of any unexpected error occurs
error = function(e) {
cat("Error occurred:", e$message, "\n")
}
)
Output:
Warning: Non-numeric values encountered.
[1] 34
Warning message:
In doTryCatch(return(expr), name, parentenv, handler) :
NAs introduced by coercion
The above code starts by defining a vector `char_vector` containing elements as characters.
- The `tryCatch()` block is used to encapsulate the main logic of the code and to handle error efficiently.
- The code converts the character values in the `char_vector` into numeric using the `as.numeric()` function. These values are stored in the `numeric_vector.
- Now if there are any values in the `char_vector` which cannot be converted into numeric they are converted into `NA`(Not Available). In this case the element `geeks` will be converted to NA.
- The code then checks if there is any NA present in `numeric_vector`. If so, then a warning is generated which is visible in the output window.
- Furthur the code removes the NA values from the `numeric_vector` using the logical indexing. Only the non-NA values are assigned to `numeric_vector`.
- The sum() function calculates the sum of values in `numeric_vector`.
- The error handler function will only be called if any error occurs during the execution of the code inside the`tryCatch()`.
Similar Reads
How to Fix in R: Argument is not numeric or logical: returning na
In this article, we are going to see how to fix in R argument is not numeric or logical returning na. This is the warning message that you may face in R. It takes the following form: Warning message: In mean.default(dataframe) : argument is not numeric or logical: returning NA The R compiler produce
3 min read
How to Manage Argument Length Zero Error in R Programming
In R Programming Language, encountering errors is common, especially for beginners and seasoned developers. One such error that often perplexes programmers is the Argument Length Zero Error. This error occurs when a function or operation expects arguments to be provided, but none are supplied, resul
3 min read
How to Solve print Error in R
The print function in R Programming Language is an essential tool for showing data structures, results, and other information to the console. While printing in R errors can happen for several reasons. Understanding these issues and how to solve them is necessary for effective R programming. In this
2 min read
How to Fix: Error in select unused arguments in R?
In this article, we will be looking toward the approach to fix the error in selecting unused arguments in the R programming language. Error in selecting unused arguments: The R compiler produces this error when a programmer tries to use the select() function of the dplyr package in R provided that t
2 min read
How to Resolve append Error in R
A flexible tool for appending elements to vectors and data frames in R Programming Language is the append() function. Errors are sometimes encountered throughout the appending procedure, though. This tutorial aims to examine frequent append() mistakes and offer workable fixes for them. Append Error
2 min read
How to Resolve Object Not Found Error in R
The "Object Not Found" error in R occurs when you try to call a variable, function, or dataset that does not exist or is not accessible in the current environment , it is a common issue especially for beginners but usually easy to fix a few simple checks.Common Causes & Solutions1. Typing Mistak
3 min read
How to Resolve colnames Error in R
R Programming Language is widely used for statistical computing and data analysis. It provides a variety of functions to manipulate data efficiently. In R, colnames() is a function used to get or set the column names of a matrix or a data frame. It allows users to access, modify, or retrieve the nam
6 min read
How to Fix in R: Arguments imply differing number of rows
In this article, we are going to see how to fix  Arguments that imply differing numbers of rows in R Programming Language. One error that we may encounter in R is: arguments imply differing number of rows: 6, 5 The compiler produces such an error when we try to create a data frame and the number of
2 min read
How to Resolve cor Error in R
The R cor function calculates the correlation coefficient between two numerical variables. Correlation is the strength and direction of the linear relationship between variables, ranging from -1 (perfect negative relationship) to 1 (perfect positive relationship) and 0 (no correlation).Common Causes
3 min read
How to solve Error in Confusion Matrix
In this article, we will discuss what is Confusion Matrix and what are the causes of the error in a Confusion Matrix and How to solve an Error in a Confusion Matrix in R Programming Language. What is Confusion Matrix?A confusion matrix is an essential tool for assessing a model's performance in mach
3 min read