forked from perlatex/R_for_Data_Science
-
Notifications
You must be signed in to change notification settings - Fork 0
/
beauty_of_across3.Rmd
120 lines (85 loc) · 2.02 KB
/
beauty_of_across3.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# tidyverse中的across()之美3 {#beauty-of-across3}
```{r beauty-of-across3-1}
library(tidyverse)
```
## 问题
计算每天水分和食物的所占比例, 比如第一天water和food都是10.0,那么各自比例都是50%.
```{r beauty-of-across3-2}
d <- tibble::tribble(
~water, ~food,
10.0, 10.0,
12.1, 10.3,
13.5, 19.1,
17.4, 16.0,
25.8, 15.6,
27.4, 19.8
)
d
```
## 传统的方法
传统的方法是,把数据框旋转成长表格,计算所占比例后,再旋转回来
```{r beauty-of-across3-3}
d %>%
rownames_to_column() %>%
pivot_longer(
cols = !rowname
) %>%
group_by(rowname) %>%
mutate(
percent = 100 * value / sum(value)
) %>%
ungroup() %>%
pivot_wider(
names_from = name,
values_from = c(value, percent),
names_glue = "{name}_{.value}"
)
```
## across的方法
传统的方法,用到基本的dplyr函数,思路很清晰,但有点周折。下面,我列出几个比较新颖的方法,当然这些方法都来源于强大across()函数
### 方法1
```{r beauty-of-across3-4}
d %>%
mutate(100 * across(.names = "%{.col}") / rowSums(across())) %>%
ungroup()
```
### 方法2
```{r beauty-of-across3-5}
rowPercent <- function(df) {
df / rowSums(df) * 100
}
d %>%
mutate(rowPercent(across(.names = "%{.col}")))
```
### 方法3
```{r beauty-of-across3-6}
d %>%
rowwise() %>%
mutate(100 * across(.names = "%{.col}") / sum(c_across())) %>%
ungroup()
```
### 方法4
```{r beauty-of-across3-7}
scale <- function(x) {
100 * x / sum(x, na.rm = TRUE)
}
d %>%
rowwise() %>%
mutate(
scale(across(.names = "%{.col}"))
)
```
### 方法5
```{r beauty-of-across3-8}
d %>%
rowwise() %>%
mutate(100 * proportions(across(.names = "%{.col}")))
```
```{r beauty-of-across3-98, echo = F}
# remove the objects
# ls() %>% stringr::str_flatten(collapse = ", ")
rm(d, scale, rowPercent)
```
```{r beauty-of-across3-99, echo = F, message = F, warning = F, results = "hide"}
pacman::p_unload(pacman::p_loaded(), character.only = TRUE)
```