通过组合所有数据框中的相似条目,从列表中形成新的数据框

Form new dataframes from list by combining similar entries in all dataframes

我有一个包含许多数据框的列表(下面提供了示例)。

    G100=structure(list(Return.Period = structure(c(4L, 6L, 2L, 3L, 5L, 
        1L), .Label = c("100yrs", "10yrs", "20yrs", "2yrs", "50yrs", 
        "5yrs"), class = "factor"), X95..lower.CI = c(54.3488053692529, 
        73.33363378538, 84.0868168935697, 91.6191228597281, 96.3360349026068, 
        95.4278817251266), Estimate = c(61.6857930414643, 84.8210149260708, 
        101.483909733627, 118.735593472652, 143.33257990536, 163.806035490329
        ), X95..upper.CI = c(69.0227807136758, 96.3083960667617, 118.881002573685, 
        145.852064085577, 190.329124908114, 232.18418925553)), .Names = c("Return.Period", 
        "X95..lower.CI", "Estimate", "X95..upper.CI"), row.names = c(NA, 
        -6L), class = "data.frame")

G101<-G100 # just for illustration

mylist=list(G100,G101) # there 100 of these with differet codes

names(mylist) 表示 "SITE"。从每个数据帧中,我想采用 "Estimate" 并形成一个看起来像这样的新数据帧(不准确,因为所有 dfs 的值都不相同): 估计<-

SITE    X2yrs    X5yrs   X10yrs   X20yrs   X50yrs X100yrs
G100 61.68579 84.82101 101.4839 118.7356 143.3326 163.806
G101 61.68579 84.82101 101.4839 118.7356 143.3326 163.806

请注意 SITEmylist 中的数据框名称相同。

"X95..lower.CI""X95..upper.CI" 执行相同的操作。

所以,我最终会得到 3 个具有上述布局的数据帧 "Estimate""X95..lower.CI""X95..upper.CI".

#lapply, rbindlist,cbind and others can do but how?

请多多指教。

只需使用 for 循环添加名称即可。可能有一种奇特的 *apply 方式,但 for 易于使用、记忆和理解。

首先添加姓名:

names(mylist) = paste0("G", seq(from = 100, by = 1, length.out = length(mylist)))

像以前一样添加 SITE 列:

for (i in seq_along(mylist)) {
    mylist[[i]]$SITE = names(mylist)[i]
}

合并数据帧:

由于您有很多数据帧或它们相当大,请使用 dplyr::rbind_all 提高速度。 (在 base R 中,do.call(rbind, mylist) 可以工作,但速度较慢。)

library(dplyr)
combined = bind_rows(mylist)

(旧版本的 dplyr 可以使用 rbind_all 而不是 bind_rows,但这很快就会被弃用:(https://github.com/hadley/dplyr/issues/803)。)

将估算值和 CI 列从长列转换为宽列。

使用 tidyr 很容易,尽管 reshape2::dcast 的工作方式类似:

library(tidyr)
Estimate = combined %>% select(SITE, Return.Period, Estimate) %>%
    spread(key = Return.Period, value = Estimate)
head(Estimate)
# Source: local data frame [2 x 7]
#
#   SITE  100yrs    10yrs    20yrs     2yrs    50yrs     5yrs
# 1 G100 163.806 101.4839 118.7356 61.68579 143.3326 84.82101
# 2 G101 163.806 101.4839 118.7356 61.68579 143.3326 84.82101    

Lower95 = combined %>% select(SITE, Return.Period, X95..lower.CI) %>%
    spread(key = Return.Period, value = X95..lower.CI)
head(Lower95)
# Source: local data frame [2 x 7]
#
#   SITE   100yrs    10yrs    20yrs     2yrs    50yrs     5yrs
# 1 G100 95.42788 84.08682 91.61912 54.34881 96.33603 73.33363
# 2 G101 95.42788 84.08682 91.61912 54.34881 96.33603 73.33363

您可能希望不按字母顺序对列重新排序。

Do the same for ``"X95..upper.CI"`.

仍然留作 reader 的练习。