【问题标题】:R Get Sum of Data frame Column By Another Column VariableR通过另一个列变量获取数据框列的总和
【发布时间】:2020-05-31 09:38:43
【问题描述】:

所以我需要将数据框与两个感兴趣的特定列相加
Col1 : 数值数据
Col2 : 年

所以我需要按年份列中提到的年份来计算数值数据的总和。 然后我需要在 y 轴上绘制聚合,在 x 轴上绘制年份。
我尝试了以下方法:

agg <- tapply(Col1, Col2, FUN=sum)

但我无法在图中的 x 轴上显示年份名称。
在我找到的一个解决方案中,使用了以下公式:

aggregate(Col1 ~ Col2,Dataframe, FUN=sum)

有人能解释一下这个公式是如何工作的吗? 我了解~ 在绘图中的使用,但不是在这个公式中。

【问题讨论】:

    标签: r dataframe plot


    【解决方案1】:

    对于aggregate() 函数,波浪号运算符基本上告诉 R 将 Col1 的值与 Col2 相加。 然后绘制你只需做plot(Col1 ~ Col2, Dataframe)

    以模拟数据为例:

    #data.frame with numeric data and years
    d <- data.frame(year = rep(2010:2020, each = 5),
                    value = rnorm(55))
    
    #aggregate to calculate sum per year
    d2 <- aggregate(value ~ year, d, sum)
    
    #plot the results (as a line graph)
    plot(value ~ year, d2, type = 'l')
    

    希望我正确理解了您的问题并解决了它。

    【讨论】:

      【解决方案2】:

      这是一个 dplyr 解决方案:

      library(ggplot2);library(dplyr)
      

      数据

      data = tibble(year = c(sample(c(2000:2020), size = 20)), numericData = runif(20, 0, 100))
      

      聚合和绘制

      data %>%
        group_by(year) %>%
        summarise(aggregated = sum(numericData)) %>%
        ggplot(aes(year, aggregated)) +
        geom_line()
      

      PS:提供一些示例代码或数据总是有帮助的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 2020-09-06
        • 2020-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多