精明的大白菜 · JS获取点击事件的内容_js点击事件获取当前元素· 3 周前 · |
气宇轩昂的大海 · 『现学现忘』Git基础 — 25、git ...· 1 周前 · |
个性的单杠 · git - git log ...· 1 周前 · |
高兴的黄豆 · Git 历史与日志管理教程 | LabEx· 1 周前 · |
绅士的水煮肉 · Sequence 使用、原理全面解析 · ...· 1 周前 · |
喝醉的卤蛋 · SQL Server ...· 1 月前 · |
率性的山楂 · 扇子 - 生活精品及 Vivienne ...· 4 月前 · |
听话的跑步鞋 · 使用Matlab的自带函数生成高斯滤波器处理 ...· 7 月前 · |
酒量小的石榴 · hdock网站复现学习笔记-CSDN博客· 7 月前 · |
刚毅的馒头 · Cannot access ...· 1 年前 · |
vector django test log |
https://www.geeksforgeeks.org/how-to-solve-argument-not-numeric-or-logical-error-in-r/ |
个性的韭菜
8 月前 |
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.
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.
# 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.
# 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.
# 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
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.
# 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
# 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.
# 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
- Company
- About Us
- Legal
- Careers
- In Media
- Contact Us
- Advertise with us
- GFG Corporate Solution
- Placement Training Program
- Explore
- Hack-A-Thons
- GfG Weekly Contest
- DSA in JAVA/C++
- Master System Design
- Master CP
- GeeksforGeeks Videos
- Geeks Community
- DSA
- Data Structures
- Algorithms
- DSA for Beginners
- Basic DSA Problems
- DSA Roadmap
- Top 100 DSA Interview Problems
- DSA Roadmap by Sandeep Jain
- All Cheat Sheets
- Python Tutorial
- Python Programming Examples
- Python Projects
- Python Tkinter
- Web Scraping
- OpenCV Tutorial
- Python Interview Question
- Computer Science
- Operating Systems
- Computer Network
- Database Management System
- Software Engineering
- Digital Logic Design
- Engineering Maths
- Competitive Programming
- Top DS or Algo for CP
- Top 50 Tree
- Top 50 Graph
- Top 50 Array
- Top 50 String
- Top 50 DP
- Top 15 Websites for CP
- Preparation Corner
- Company-Wise Recruitment Process
- Resume Templates
- Aptitude Preparation
- Puzzles
- Company-Wise Preparation
- Management & Finance
- Management
- HR Management
- Finance
- Income Tax
- Organisational Behaviour
- Marketing
- Free Online Tools
- Typing Test
- Image Editor
- Code Formatters
- Code Converters
- Currency Converter
- Random Number Generator
- Random Password Generator
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
Please go through our recently updated Improvement Guidelines before submitting any improvements.
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article's discussion tab.
You will be notified via email once the article is available for improvement.
Thank you for your valuable feedback!
Please go through our recently updated Improvement Guidelines before submitting any improvements.
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
精明的大白菜 · JS获取点击事件的内容_js点击事件获取当前元素 3 周前 |
高兴的黄豆 · Git 历史与日志管理教程 | LabEx 1 周前 |
酒量小的石榴 · hdock网站复现学习笔记-CSDN博客 7 月前 |