applying a created function in a list with data frames

Viewed 40

I would like to calculate the variation coefficient in a list composed of several data frames. However, when I apply my function that calculates the variation coeficient in my list of data frames I am getting this error:

coef_var = lapply(dists_log, cvs) 
Error in is.data.frame(x) : 
  'list' object cannot be coerced to type 'double' 

Here what I did:

List = list  (A = data.frame(A = rnorm(30), B = rnorm(30), C =rnorm (30), D = rnorm(30)),
       B = data.frame(A = rnorm(30), B = rnorm(30), C =rnorm (30), D = rnorm(30)),
       C = data.frame(A = rnorm(30), B = rnorm(30), C =rnorm (30), D = rnorm(30)),
       D = data.frame(A = rnorm(30), B = rnorm(30), C =rnorm (30), D = rnorm(30)))

#function to calculate the variation coeficient
cvs <- function (dist){
  cv  <-  sd(dist, na.rm=T) / mean(dist, na.rm=T) * 100
  return(cv)
}

The I run:
coef_var = lapply(dists_log, cvs)

and got the error message above

Can someone help me with this error?

1 Answers

We need a nested list as sd and mean requires the input to be vector and not a data.frame. So, we loop over the columns of the data.frame with lapply, apply the 'cvs' function, assign back to the object and return the data.frame object

lapply(dists_log, function(x) {x[] <- lapply(x, cvs); x})

If we are expecting only a single element as output

lapply(dists_log, function(x) unlist(lapply(x, cvs)))
Related