【问题标题】:Create Histogram, grouping by a column and then sum by another in R创建直方图,按列分组,然后在 R 中按另一个求和
【发布时间】:2020-05-14 00:39:17
【问题描述】:

我有一个数据集,data,具有以下值:

               ID                TIME                         Duration   
                A                12/18/2019 4:45:10 AM        1 sec
                A                12/18/2019 4:45:11 AM        0 sec
                A                12/18/2019 9:06:59 PM        0 sec                    
                B                12/18/2019 4:14:13 AM        1 sec
                B                12/18/2019 4:14:14 AM        0 sec

我希望创建一个直方图,对 ID 进行分组,并对 Duration 求和,如下所示,其中 ID 为 X 轴,Y 轴为 Sum,使用 ggplot。

               ID        Sum

               A         1
               B         1

我使用了以下代码:

              library(dplyr)
              library(ggplot)
              library(qplot)




            sumdata<-df %>% groupby(ID) %>% SUM(Duration)

            qplot(df,
            geom="histogram",
            binwidth = 0.5,  
            main = "Histogram for Duration", 
            xlab = "ID"
            ylab = "Duration")

我还在研究。任何建议表示赞赏。

【问题讨论】:

  • dput您的问题中的数据框。
  • 试试sumdata &lt;- df %&gt;% group_by(ID) %&gt;% mutate(sums = sum(Duration)) %&gt;% ungroup() %&gt;% ggplot(aes(x = ID, y = sums)) + geom_bar(stat = "identity")

标签: r ggplot2 dplyr histogram


【解决方案1】:

base R 的选项

aggregate(.~ ID, df, FUN = sum)

【讨论】:

  • 谢谢,下面的代码会group_by ID然后执行SUM?
  • @TanishaHudson。如果只是单列 aggregate(duration ~ ID, df, FUN = sum) 其中 ID 是分组列
  • 应该是ggplot(df, aes(ID, Duration)) + geom_bar(stat = 'identity')
  • @TanishaHudson 如果是POSIXct 类而不是POSIXlt
  • @TanishaHudson 如果“时间”值都是唯一的,那么每组的行数就会。是1。即你能aggregate(Duration ~ Time + ID, df, FUN = length)
【解决方案2】:

您可以为此使用ggplot2

在绘图之前像这样总结数据:

library(dplyr)
 df <- df %>%
   group_by(ID) %>%
   summarise_all(sum)

然后创建一个情节。

library(ggplot2)
 ggplot(data = df, aes(x = ID, y = Duration)) +
   geom_bar(stat = "identity")

【讨论】:

  • 嗨,第一个命令出现此错误:Summary.POSIXct(1579113995, na.rm = FALSE) 中的错误:未为“POSIXt”对象定义“总和”
  • 您能否添加可重现的数据示例?或者,您可以使用上面给出的aggregate 解决方案,然后使用ggplot2 绘制图形。
  • 谢谢,我不得不这样做:我想我必须这样做:ggplot(data = df, aes(df$ID, df$Duration)) + geom_bar(stat = "identity")指定我相信的列
  • 见这个例子:df &lt;- data.frame(ID = c("A", "A", "A", "B", "B"), Time = c(1, 2, 3, 4, 5), Duration = c(1, 0, 0, 1, 0))library(ggplot2) ggplot(data = df, aes(x = ID, y = Duration)) + geom_bar(stat = "identity")。它适用于我的机器。我正在使用ggplot2 版本'3.2.1'。
  • 试试这个:ggplot(data = df, aes(x = ID, y = Duration)) + geom_bar(stat = "identity") + coord_flip()。它将 x 轴列更改为 y 轴,可以解决您的问题。
猜你喜欢
  • 1970-01-01
  • 2020-12-14
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多