【问题标题】:applying a created function in a list with data frames在带有数据框的列表中应用创建的函数
【发布时间】:2021-08-02 06:20:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: r list dataframe apply


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我的猜测是 lapply(dists_log, function(x) sapply(x, cvs)) 可能是 OP 想要的,因为 CV 只是每一列的单个值。
    • 谢谢@akrun 和@Adam。两种解决方案(lapply(dists_log, function(x) unlist(lapply(x, cvs)))lapply(dists_log, function(x) sapply(x, cvs)) 都运行良好。
    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多