【问题标题】:hist() within piping and group_by in dplyrdplyr 中的管道和 group_by 中的 hist()
【发布时间】:2018-01-18 22:20:30
【问题描述】:

我正在寻找一种方法来利用 dplyrgroup_by 功能进行计数,以及在 grouping_by gearvs 之后为 mpg 绘制无图直方图。

我的代码是:

mtcars %>% 
group_by(gear,vs) %>% 
summarise(counts = count (n), hist(mpg, plot = FALSE, breaks = c(seq(10,40,1))))

错误是:

summarise_impl(.data, dots) 中的错误: 列 hist(mpg, plot = FALSE, breaks = c(seq(10, 40, 1)))` 的长度必须为 1(汇总值),而不是 6

我并不局限于dplyr,但这就是我目前在 R 中所熟悉的全部内容。

感谢任何帮助。

【问题讨论】:

  • 你能不能编辑一下,去掉 plot-less 对我来说它是直方图的对立面!

标签: r dplyr histogram


【解决方案1】:

我不太确定什么是无图直方图,但这有帮助吗?

mtcars %>%
    mutate(mpgClasses = cut(mpg, 10:40)) %>%
    group_by(gear, vs, mpgClasses) %>%
    summarise(n())

你也可以像这样重新排列

mtcars %>%
    mutate(mpgClasses = cut(mpg, 10:40)) %>%
    group_by(gear, vs, mpgClasses) %>%
    summarise(counts = n()) %>%
    spread(mpgClasses, counts)

如果你能多描述一点,你的目标是什么,我们可以找到更好的解决方案。

【讨论】:

  • 基本图形函数hist 返回因子计数。见hist
【解决方案2】:

在这里,我只是从hist 中提取counts。由于我必须为每个组设置一个元素,因此我将其列了一个列表。

library(dplyr)
x <- mtcars %>% group_by(gear,vs) %>%     
   summarise(counts = n(),
             hcounts =  list(hist(mpg, plot = FALSE, breaks = c(seq(10,40,1)))$counts))

x
# # A tibble: 6 x 4
# # Groups:   gear [?]
# gear    vs counts    hcounts
# <dbl> <dbl>  <int>     <list>
#   1     3     0     12 <int [30]>
#   2     3     1      3 <int [30]>
#   3     4     0      2 <int [30]>
#   4     4     1     10 <int [30]>
#   5     5     0      4 <int [30]>
#   6     5     1      1 <int [30]>

x$hcounts
# [[1]]
# [1] 2 0 0 1 2 3 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# 
# [[2]]
# [1] 0 0 0 0 0 0 0 0 1 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# 
# [[3]]
# [1] 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# 
# [[4]]
# [1] 0 0 0 0 0 0 0 1 0 1 0 1 2 0 1 0 0 1 0 0 1 0 1 1 0 0 0 0 0 0
# 
# [[5]]
# [1] 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# 
# [[6]]
# [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多