rtapply

How to find the coefficient of variation using the tapply function in R


I am trying to find the coefficient of variation in abundance using tapply in R and tried this code:

tapply(ReefFish$count, ReefFish$commonname, FUN = 100*sd(x)/mean(x))

However, I get the error:

Error in is.data.frame(x) : object 'x' not found

I am not sure what to put as 'x' since I am looking for the coefficient of variation in abundance (count) by their common name (commonname).

Does anyone know how I am supposed to define x in this code?


Solution

  • I think you are looking for an anonymous function with a variable x.

    tapply(ReefFish$count, ReefFish$commonname, function(x) 100*sd(x)/mean(x))