【问题标题】:Iteratively rbind 10% of the data from data frame and plotting迭代地从数据框中 rbind 10% 的数据并绘图
【发布时间】:2015-12-18 15:02:07
【问题描述】:

我有三个数据框,每个数据框都有 1 列,但 df1、df2、df3 的行数不同,分别为 100,100,1000。我想迭代地做一个 rbind 并通过每次取 10% 的数据来重复计算小块数据的平均值之类的度量。这意味着在第一次迭代中,我需要 df1 中的 10 行、df2 中的 10 行和 df3 中的 100 行,对于这个集合,我需要得到一个平均值,并且该过程应该继续 10 次。而且我需要随着时间的推移绘制迭代块,以显示迭代中 y 轴的平均值,并通过此过程获得总体平均值。有什么建议?

df1<- data.frame(A=c(1:100))
df2<- data.frame(A=c(1:100))
df3<- data.frame(A=c(1:1000))

library(dplyr)
for i in (1:10)
     { df[i]<- rbind_list(df1,df2,df3)
      mean=mean(df$A)} 

【问题讨论】:

    标签: r dataframe dplyr rbind


    【解决方案1】:

    您试图保持单独的数据框使事情变得复杂。添加一个“组”列——如果您愿意,可以将其称为“迭代”——并将您的数据放在一个数据框中:

    df1$group = rep(1:10, each = nrow(df1) / 10)
    df2$group = rep(1:10, each = nrow(df2) / 10)
    df3$group = rep(1:10, each = nrow(df3) / 10)
    df = rbind(df1, df2, df3)
    
    means = group_by(df, group) %>% summarize(means = mean(A))
    means
    #  Source: local data frame [10 x 2]
    #
    #     group means
    #  1      1    43
    #  2      2   128
    #  3      3   213
    #  4      4   298
    #  5      5   383
    #  6      6   468
    #  7      7   553
    #  8      8   638
    #  9      9   723
    # 10     10   808
    

    您的总体平均值为mean(df$A)。您可以使用with(means, plot(group, means)) 进行绘图。

    编辑:

    如果组不完全正确,我将按以下方式分配组列。确保您的 dplyr 是最新的,这使用了 bind_rows().id 参数,这是本月在 0.4.3 版中新增的。

    library(dplyr)
    # dplyr > 0.4.3
    
    df = bind_rows(df1, df2, df3, .id = "id")
    df = df %>% group_by(id) %>%
        mutate(group = (0:(n() - 1)) %/% (n() / 10) + 1)
    

    id 列告诉您该行来自哪个数据框,group 列将其分成 10 个组。上面的其余代码应该可以正常工作。

    【讨论】:

    • 谢谢!我有奇数,所以不知何故无法将它们分组。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2014-06-02
    • 2020-10-08
    • 2021-11-21
    • 2019-07-24
    • 2022-01-17
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多