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
的 assd
并且mean
要求输入是vector
而不是 data.frame。因此,我们遍历data.frame
with的列lapply
,应用 'cvs' 函数,分配回对象并返回 data.frame 对象
lapply(dists_log, function(x) {x[] <- lapply(x, cvs); x})
如果我们只期望一个元素作为输出
lapply(dists_log, function(x) unlist(lapply(x, cvs)))
推荐阅读
- angularjs - Angular JS:错误:意外请求:GET 模板/login.html
- postgresql - Golang GORM 搜索条件
- laravel - 如何使用 Eloquent 保存 OneToMany 关系
- python - 如何在不创建数据副本的情况下 pd.merge?
- python - Pandas - 根据日期差异返回 x 列
- c++ - syscall.MustLoadDll.MustFindProc 抛出“找不到指定的过程”
- elasticsearch - 用于弹性搜索的边缘 N-gram 中的连字符
- bash - 打开 tmux 终端的快捷方式
- ios - 线程 1:致命错误:NSArray 元素无法匹配 Swift Array 元素类型
- xamarin - 绑定文本未以 xamarin 形式显示