【问题标题】:Can dplyr summarise over several variables and list of tables可以 dplyr 总结几个变量和表格列表
【发布时间】:2017-09-08 01:43:57
【问题描述】:

我一直在尝试使用 dplyr 在具有相同结构的表列表中汇总多个表:

LUZ_code  Type1  Type2 Type3 Type4 country
AT001L2  90142 752310 70700  7368      AT
AT002L2  82693 193892 30264   496      AT
AT003L2 119690 203394 28737   420      AT
AT004L2  42259  85892 14512   189      AT
AT005L2 113768  59841 15464   224      AT
AT006L1 126001 102170  9344   134      AT

我已经在脚本中应用了几个 lapply,所以现在我在一个名为国家的列表中拥有了这些表。

如果我尝试使用循环:

for (i in 1:length(countries)){
  years <- c("2010", "2030", "2030_ECL")
  db <- as.data.frame(countries[i])[,-1]
  db <- db %>%
    group_by(country) %>%
    summarise_each(funs(sum))
write.table(db, paste("country_conc",years[i], ".txt", sep = ""), 
          col.names = TRUE, row.names = FALSE, sep = "\t", quote = FALSE)
}

这似乎没有问题,但我想知道是否有办法使用 lapply。到目前为止,我的尝试是:

summarise <- function (db){
 db <- (db)[,-1]
 db <- db %>%
   group_by(country) %>%
   summarise_each(funs(sum))
 return (db)
}
total <- lapply (concentration, summarise)`

我收到此错误消息:

汇总错误(tbl, Type1 = sum(Type1), Type2 = sum(Type2), Type3 = sum(Type3), : 未使用的参数 (Type1 = sum(Type1), Type2 = sum(Type2), Type3 = sum(Type3), Type4 = sum(Type4))"

感谢您的帮助,

【问题讨论】:

  • concentrationlapply 调用中是什么?
  • 你为什么不bind_rows 表列表(同时分配一个id)然后计算摘要?
  • 您可以使用summarise_at()summarise_if() 指定要汇总的列。

标签: r dplyr lapply


【解决方案1】:

我让它工作正常。我同意@akrun,我不知道concentration 是什么。我认为将其更改为 countries 可能会解决您的问题。这是我的工作示例。

c1 <- "LUZ_code  Type1  Type2 Type3 Type4 country
AT001L2  90142 752310 70700  7368      AT
AT002L2  82693 193892 30264   496      AT
AT003L2 119690 203394 28737   420      AT
AT004L2  42259  85892 14512   189      AT
AT005L2 113768  59841 15464   224      AT
AT006L1 126001 102170  9344   134      AT"

t1 <- read.table(text = c1, header = T)

t4 <- t3 <- t2 <- t1
t2$country <- "ZZ"
t3$country <- "YY"
t4$country <- "XX"

countries <- list(t1, t2, t3, t4)

mySummarise <- function (db){
 db <- (db)[,-1]
 db <- db %>%
   group_by(country) %>%
   summarise_each(funs(sum))
 return (data.frame(db))
}
total <- lapply (countries, mySummarise)
do.call(rbind.data.frame, total)

【讨论】:

  • 在使用 dplyr 时定义自己的 summarise 函数可能不是一个好主意,作为旁注
  • 抱歉有点乱,集中其实是国家。我还意识到该表并不能反映全局:国家是可变的(AT、BE、DK 等多达 28 个国家),我想总结所有变量 Type1...Type4 按国家分组,所以在实践中我应该得到一个有 28 行和 5 列的表格,一个代表国家,一个代表每个汇总类型
  • 好的。我编辑考虑到@docendodiscimus 的评论。我还进行了编辑,因此该函数返回了一个数据框。所以你现在得到一个列表,其中包含可能的数据框作为元素。然后,您只需将该列表转换为数据框或数据表。
猜你喜欢
  • 2014-02-13
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多