Tibble数据类型的逐行求和

时间:2017-01-07 05:55:57

标签: r dplyr

我有一个Tibble,我注意到dplyr::rowwise()sum()的组合不起作用。我知道这个主题有很多主题,我有2到3个解决方案,但我不完全是rowwise()sum()的组合不起作用的原因。

所以,我的问题是:为什么rowwise()sum()的组合不起作用,我们可以做些什么才能使其发挥作用?我是初学者,所以我相信我在下面的代码中做错了。

数据:

dput(data)
structure(list(Fiscal.Year = c(2016L, 2016L, 2016L, 2016L, 2016L, 
2016L, 2016L, 2016L, 2016L, 2016L), col1 = c(0, 26613797.764311, 
0, 12717073.587292, 0, 0, 0, 0, 0, 0), col2 = c(0, 0, 0, 0, 8969417.89721166, 
0, 11483606.8417117, 0, 0, 0), col3 = c(0, 0, 33251606.347943, 
0, 25082683.4492186, 0, 17337191.3014127, 0, 0, 0), col4 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), col5 = c(0, 0, 0, 0, 0, 0, 0, 0, 
0, 9796823.229998), col6 = c(35822181.695755, 17475066.870565, 
0, 0, 0, 0, 4040695.327278, 0, 13117249.623068, 0), col7 = c(0, 
0, 0, 0, 0, 18347258.910001, 0, 0, 7002205.087399, 0), No.Trans = c(2987L, 
1292L, 1002L, 796L, 691L, 677L, 400L, 388L, 381L, 366L)), .Names = c("Fiscal.Year", 
"col1", "col2", "col3", "col4", "col5", "col6", "col7", "No.Trans"
), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

此代码不起作用:

data %>%  #No
        dplyr::rowwise() %>%
        dplyr::mutate(sum = sum(.[2:8]))

仅供参考,我尝试了以下一组代码,它们可以正常工作。我特意寻找使用rowwise()sum()的解决方案。

选项1: 讨论于:Summarise over all columns

  data %>%
    dplyr::rowwise() %>%
    do(data.frame(., res = sum(unlist(.)[2:8])))

选项2:

  rowSums(data[,2:8])

选项3: 讨论于:How to do rowwise summation over selected columns using column index with dplyr?

  data %>% mutate(sum=Reduce("+",.[2:8]))

选项4:

data %>%
        select(2:8)%>%
        dplyr::mutate(sum=rowSums(.))

1 个答案:

答案 0 :(得分:2)

这些专栏看起来很像观察...... 如果是这样,整理数据帧将使数据争论变得更加容易。

这能为您提供所需的答案吗?

data %>%
    gather(key = col, val = revenue, `col1`:`col7`) %>%
    group_by(Fiscal.Year, No.Trans) %>%
    summarise(res = sum(revenue))

Source: local data frame [10 x 3]
Groups: Fiscal.Year [?]

   Fiscal.Year No.Trans      res
         <int>    <int>    <dbl>
1         2016      366  9796823
2         2016      381 20119455
3         2016      388        0
4         2016      400 32861493
5         2016      677 18347259
6         2016      691 34052101
7         2016      796 12717074
8         2016     1002 33251606
9         2016     1292 44088865
10        2016     2987 35822182

为了整整顺利地介绍一下,请尝试here。他在演讲中讨论的功能已经更新,但是Hadley在教授这门课程方面做得很好:通过教学链接,就像它一样。

更新的功能可以在他的 ggplot2 一本书here中找到。