【问题标题】:How to calculate means from a column in a list of lists? [closed]如何从列表列表中的列计算平均值? [关闭]
【发布时间】:2020-09-26 14:14:49
【问题描述】:

我以列表的形式生成了一个包含 203 个单个数据表的列表。我用 sapply 创建它,它看起来像这样:

在每个表格中,我想选择 slope_CC 值(它复制了它,所以它的值相同了几次)。我计算它们的平均值而不是选择其中之一,因为它更容易。目标是在一个新的数据表中拥有所有手段。这些表有不同的行号。

First_table <- slope_list$selected0.csv

get_means_fun <- function(First_table){
  N <- First_table[["slope_CC"]]
  mean <- mean(N)
  return(data.frame(mean))
}

list_select <- lst(pattern=".csv", slope_list)
get_means <- lapply(list_select, get_means_fun)

lapply() 是最好的方法吗? 我收到此错误:First_table[["slope_CC"]] 中的错误:下标超出范围,即使我单独运行同一行时它仍然有效。

【问题讨论】:

  • 在你的函数中尝试First_table["slope_CC"]
  • 看看你的一些列表对象(例如,selected1.csv)不是data.frames,而是一个逻辑[1]?这些将在功能中失败,因为它们显然没有您想要的列。您需要事先删除它们,或者有办法在函数中跳过它们。

标签: r function lapply


【解决方案1】:

我已经做了一个我认为您正在寻找的虚拟示例。我的主要调整是,我没有取平均值,这需要 R 对每个元素求和然后除以长度,而是简单地获取第一个值。

# example data
list_select <- list(table1 = head(mtcars),
                    table2 = FALSE,
                    table3 = tail(mtcars))

# grab the first value of column "wt". switch this for your column
# this checks to see if it is a data.frame, if not, return NA
# you can change this to return a NULL, or whatever you would like.
get_value_function <- function(the_table) {
  if (is.data.frame(the_table)) the_table[["wt"]][1] else NA
}

# returns a list
lapply(list_select, get_value_function)
# $table1
# [1] 2.62
# 
# $table2
# [1] NA
# 
# $table3
# [1] 2.14

# returns a vector
sapply(list_select, get_value_function)
# table1 table2 table3 
# 2.62     NA   2.14 

我也喜欢在purrr 中做类似的事情。它省去了提前创建函数的麻烦。

library(purrr)

# returns a list like lapply
map(list_select, ~ if (is.data.frame(.x)) .x[["wt"]][1] else NA)

# returns a vector sapply
map_dbl(list_select, ~ if (is.data.frame(.x)) .x[["wt"]][1] else NA)

另一种方法是提前删除不是 data.frames 的列表元素。一个非常简单的方法,同样使用purrr,是使用keep

list_select %>% 
  keep(is.data.frame) %>% 
  map_dbl(~ .x[["wt"]][1])

# table1 table3 
# 2.62   2.14 

【讨论】:

  • 感谢您的帮助。它与 is.data.table 一起使用。但是,我认为这些输出对于进一步使用来说有点复杂。我不太习惯使用这些列表,而不是普通的数据框。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多