[英]R - how to sum each columns from df
我有這個df
df <- read.table(text="
id month gas tickets
1 1 13 14
2 1 12 1
1 2 4 5
3 1 5 7
1 3 0 9
", header=TRUE)
我想做的是計算每個月的汽油,機票(以及我的實際df中另外50多行)的總和。 通常我會做類似的事情
result <-
df %>%
group_by(month) %>%
summarise(
gas = sum(gas),
tickets = sum(tickets)
) %>%
ungroup()
但是由於我的數據框中確實有很多列,所以我不想為每列創建求和函數而重復自己。 我想知道是否可以創建一些更精美的功能-可以創建除id和month以外的每個列總和的月份組合列。
您可以使用summarise_at()
忽略id
並對其余部分求和:
df %>%
group_by(month) %>%
summarise_at(vars(-id), list(sum = ~sum))
# A tibble: 3 x 3
month gas_sum tickets_sum
<int> <int> <int>
1 1 30 22
2 2 4 5
3 3 0 9
您可以在注釋中使用標記集建議的aggregate
。 如果您想堅持tidyverse,可以嘗試以下操作:
df %>%
select(-id) %>%
group_by(month) %>%
summarise_if(is.numeric, sum)
#### OUTPUT ####
# A tibble: 3 x 3
month gas tickets
<fct> <int> <int>
1 1 30 22
2 2 4 5
3 3 0 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.