首页 > 解决方案 > 在带有数据框的列表中应用创建的函数

问题描述

我想计算由几个数据框组成的列表中的变异系数。但是,当我应用计算数据帧列表中变异系数的函数时,我收到此错误:

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

这是我所做的:

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

有人可以帮我解决这个错误吗?

标签: rlistdataframeapply

解决方案


我们需要一个嵌套list的 assd并且mean要求输入是vector而不是 data.frame。因此,我们遍历data.framewith的列lapply,应用 'cvs' 函数,分配回对象并返回 data.frame 对象

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

如果我们只期望一个元素作为输出

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

推荐阅读