CodexBloom - Programming Q&A Platform

working with 'non-numeric argument to binary operator' using custom function with `sapply` in R 4.3.1

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
r sapply custom-function error-handling R

I've tried everything I can think of but Hey everyone, I'm running into an issue that's driving me crazy....... I'm working on a project that involves applying a custom function to a list of numeric vectors using `sapply`, but I'm running into the behavior 'non-numeric argument to binary operator'. Here's a simplified version of my code: ```r custom_function <- function(x) { return(sum(x) / length(x)) } my_list <- list(a = c(1, 2, 3), b = c(4, NA, 6), c = c('text', 5, 6)) result <- sapply(my_list, custom_function) ``` When I run this, I get the following behavior: ``` behavior in custom_function(x) : non-numeric argument to binary operator ``` I've checked the contents of `my_list`, and it contains a mix of numeric and character vectors. I understand that `sapply` will pass each element of the list to `custom_function`, but I'm not sure how to handle the non-numeric vectors gracefully. I tried adding a conditional to check if the vector is numeric, but it still throws the same behavior: ```r custom_function <- function(x) { if (!is.numeric(x)) { return(NA) } return(sum(x, na.rm = TRUE) / length(x)) } ``` However, this doesn't prevent the behavior when it reaches the character vector. What’s the best way to ensure that my function only processes numeric vectors and returns NA for the non-numeric ones without throwing an behavior? Any suggestions would be greatly appreciated! I'd really appreciate any guidance on this. For context: I'm using R on Ubuntu. Am I missing something obvious? My team is using R for this microservice. What's the best practice here? My development environment is CentOS. Any feedback is welcome!