我有一个 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(.))
最佳答案
这些列看起来很像观察结果......
如果是这样,整理该数据框将使数据整理变得更加容易。
这能为您带来您正在寻找的答案吗?
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 。他在演示文稿中讨论的功能已经更新,但哈德利在教授该主题方面做得很好:可以说是通过教学链。
更新的函数可以在他的ggplot2书中找到here 。
关于Tibble 数据类型的行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518323/