本文介绍了行总和使用mutate和select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
library(dplyr)
library(dplyr)
我有以下数据:
d1 <- data_frame(
name = c("jim", "john", "jim", "john"),
`2012` = c(57, 58, 47, 57),
`2013` = c(14, 3, 3, 90))
我想使用mutate函数创建两个新行,以便获得每年的john和jim总计。我希望数据看起来像这样:
I would like to create two new rows using mutate function so that I have the totals for john and jim for each year. I would like the data to look like this:
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))
我已经尝试了以下其他事情:
I've tried the following amoungst other things:
d1 %>%
mutate(jim total = rowSums(select(., contains("jim"))))
但是我不太明白我想要。有任何想法吗?
But I'm not quite getting what I want. Any ideas?
谢谢
推荐答案
您可以先进行总结,然后再进行总结将它们绑定到原始df,即
You can summarise first and then bind them to your original df, i.e.
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
这篇关于行总和使用mutate和select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!