行总和使用mutate和select

时间:2018-09-28 09:30:07

标签: r dplyr

库(dplyr)

我有以下数据:

s = {'name': 'Spain', 'wins': 1, 'loses' : 1, 'draws': 1, 'goal, difference': 4, 'points': 4}
e = {'name': 'England', 'wins': 2, 'loses' : 1, 'draws': 0, 'goal difference': 1, 'points': 6}
p = {'name': 'Portugal', 'wins': 0, 'loses' : 1, 'draws': 2, 'goal difference': 0, 'points': 2}
g = {'name': 'Germany', 'wins': 1, 'loses' : 1, 'draws': 1, 'goal difference': 5, 'points': 4}

l = [s, e, p, g]

sorted(l, key=lambda x: (-x['points'], x['name']))

我想使用mutate函数创建两个新行,以便获得每年的john和jim总计。我希望数据看起来像这样:

d1 <- data_frame(
name = c("jim", "john", "jim", "john"),
`2012` = c(57, 58, 47, 57),
`2013` = c(14, 3, 3, 90))

在其他事情中,我尝试了以下操作:

d1 <- data_frame(
name = c("jim", "john", "jim", "john", "jim total", "john total"),
`2012` = c(57, 58, 47, 57, 104, 115 ),
`2013` = c(14, 3, 3, 90, 17, 93))

但是我还没有得到想要的东西。有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:3)

您可以先进行汇总,然后将其绑定到原始df,即

library(tidyverse)

bind_rows(d1,
           d1 %>% 
             group_by(name) %>% 
             summarise_all(funs(sum)) %>%
             mutate(name = paste0(name, '_total')))

给出,

# A tibble: 6 x 3
   name       `2012` `2013`
  <chr>       <dbl>  <dbl>
1 jim            57     14
2 john           58      3
3 jim            47      3
4 john           57     90
5 jim_total     104     17
6 john_total    115     93