Home > Back-end >  Error message with aggregate() when using my own function in R
Error message with aggregate() when using my own function in R

Time:10-14

I am a new student to R, and I am having difficulty with aggregate(), only when using a function I have written; it works fine with mean, min, etc. I'm assuming the problem is in the structure of my function 'myfun'. But 'myfun' works fine with my dataset. Any suggestions for how to fix this?

The code below includes the function I created 'myfun':

Write the function

'myfun <- function(f){   
  min <- min(f)         
  max <- max(f)         
  mean <- mean(f)      
  range <- max(f) - min(f)     
  lst <- list(min = min, max = max, mean = mean, range = range)  
  return(lst)
}'


'myfun(NoNAs$Infection)  # apply function to print min, max, mean, & range of Infection'

Question 5: Use aggregate() to calculate the corresponding values of infection for each species. Let the argument FUN be the function that you defined in question 4.

'aggregate(NoNAs$Infection, by = list(NoNAs$Species), FUN = mean)
aggregate(NoNAs$Infection, by = list(NoNAs$Species), FUN = myfun)'

Below is a snip of the dataset structure from NoNAs, in which I have already removed all rows containing an NA.

enter image description here

Thanks for any help!

CodePudding user response:

Change your function to this:

myfun <- function(f){   
  min <- min(f)         
  max <- max(f)         
  mean <- mean(f)      
  range <- max(f) - min(f)     
  lst <- c(min = min, max = max, mean = mean, range = range)  
  return(lst)
}

Since you did not provide reproducible data, we can use iris:

data(iris)
aggregate(Sepal.Width~Species, iris, myfun)
#      Species Sepal.Width.min Sepal.Width.max Sepal.Width.mean Sepal.Width.range
# 1     setosa           2.300           4.400            3.428             2.100
# 2 versicolor           2.000           3.400            2.770             1.400
# 3  virginica           2.200           3.800            2.974             1.600
  • Related