首页 文章

管道内的hist()和dplyr中的group_by

提问于
浏览
0

我正在寻找一种方法来利用 dplyrgroup_by 功能进行计数,并在分组_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的's all I' .

任何帮助表示赞赏 .

2 回答

  • 0

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

    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)
    

    如果你能描述一下,你前进的目标是什么,我们可以找到更好的解决方案 .

  • 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
    

相关问题