r-在具有数据帧的列表中应用创建的函数



我想计算由几个数据帧组成的列表中的变异系数。然而,当我在数据帧列表中应用计算变异系数的函数时,我会得到这个错误:

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

有人能帮我纠正这个错误吗?

我们需要一个嵌套的list作为sd,而mean要求输入为vector,而不是数据帧。因此,我们用lapply循环data.frame的列,应用"cvs"函数,分配回对象并返回数据帧对象

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

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

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

最新更新