r - 从第一列 dplyr 增加百分比
问题描述
我有
library(tidyverse)
gapminder <- readr::read_csv("https://raw.githubusercontent.com/OHI-Science/data-science-training/master/data/gapminder.csv")
gapminder %>%
group_by(continent, year) %>%
summarize(cont_pop = sum(pop)) %>%
arrange(year) %>%
spread(year,value =cont_pop )
我想返回自 1952 年以来的百分比增长(第一列),而不是绝对数字。纯 dplyr / tidyverse 有可能吗?
解决方案
是的,你可以这样做——
library(dplyr)
library(tidyr)
library(gapminder)
gapminder %>%
group_by(continent, year) %>%
summarise(cont_ratio = sum(pop)) %>%
mutate(cont_ratio = (cont_ratio - first(cont_ratio))/first(cont_ratio)) %>%
ungroup %>%
pivot_wider(names_from = year, values_from = cont_ratio)
# continent `1952` `1957` `1962` `1967` `1972` `1977` `1982` `1987` `1992` `1997` `2002` `2007`
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 Africa 0 0.114 0.248 0.411 0.599 0.822 1.10 1.42 1.77 2.13 2.51 2.91
#2 Americas 0 0.121 0.255 0.393 0.534 0.675 0.826 0.978 1.14 1.31 1.46 1.60
#3 Asia 0 0.120 0.216 0.366 0.542 0.709 0.871 1.06 1.25 1.42 1.58 1.73
#4 Europe 0 0.0473 0.101 0.151 0.197 0.237 0.271 0.299 0.335 0.361 0.383 0.402
#5 Oceania 0 0.118 0.243 0.366 0.507 0.613 0.721 0.832 0.958 1.08 1.19 1.30
推荐阅读
- batch-file - 使用批处理脚本将特定文件从源目录复制到目标目录和子目录
- php - 可以在 WP 表排序上查询数据库吗?
- shell - 将输入和输出重定向到缓冲区和从缓冲区重定向
- node.js - 如何在 node-postgres 中的 client.release() 末尾修复无限 Promise 循环?
- javascript - Wordpress 网站上主题之间的 Javascript 模态弹出窗口
- sage - Sage TypeError 符号计算中不允许的正特征
- python-3.x - pywinatuo - 同一属性的访问数据库匹配错误 - 代码适用于小型数据库而不适用于大型数据库
- bash - 新的 bash shell 打开时 bash 找不到函数
- haskell - 如何断言内部函数的类型取决于 Haskell 中外部函数的类型?
- scala - 是否有内置函数将 Int 限制为 Range?