Open In App

How to solve Argument not Numeric or Logical Error in R

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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()`.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads