-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0306_advanced-dplyr.Rmd
217 lines (167 loc) · 4.82 KB
/
0306_advanced-dplyr.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# Advanced **dplyr** functions
## `recode()`
`recode()` is useful for recoding categorical variables.
Unlike most of the other function in **dplyr**, `recode()` is backwards in it's syntax:
```
recode(.x, old = new)
```
Lets take a look at recoding different variables using the `psychTools::bfi` dataset:
In the dataset, our `gender` variable has values 1 and 2.
This is a little vague since we don't know what 1 or 2 is in respect to gender.
```{r}
dat_bfi <- psychTools::bfi |>
rownames_to_column(var = ".id")
dat_bfi |>
mutate(
gender = recode(gender, "1" = "man", "2" = "woman")
) |>
select(.id, gender, education) |>
head()
```
*Note that for numeric values on the left side of `=`,*
*you need to wrap them in "quotes" or `backticks`;*
*however, that's not necessary for character values*
We can also specify a `.default` value within our `recode()`.
For example, say we want to have just "HS or less" versus "more than HS"
```{r}
dat_bfi |>
mutate(
education = recode(education, "1" = "HS", "2" = "HS", .default = "More than HS")
) |>
select(.id, gender, education) |>
head()
```
Another neat feature of the `recode()` function is the `.missing` value.
If we would rather convert NA values to something more explicit,
we can specify that in the `.missing` argument.
```{r}
dat_bfi |>
mutate(
education = recode(
education,
"1" = "HS",
"2" = "HS",
.default = "More than HS",
.missing = "(Unknown)"
)
) |>
select(.id, gender, education) |>
head()
```
Or we can use `tidyr::replace_na()`
```{r}
dat_bfi |>
mutate(
education = replace_na(education, replace = "(Unknown)")
) |>
select(.id, gender, education) |>
head()
```
## `across()`
The `across` function allows us to apply transformations across multiple columns
Say we wanted to look at the mean of each agreeable variable between gender groups:
```{r}
dat_bfi |>
group_by(gender) |>
summarize(
across(
A1:A5,
mean,
na.rm = TRUE
)
)
```
If we want to put the function name `mean`, togther with all of its arguments,
we can write it as an **anonymous function**:
```{r}
dat_bfi |>
group_by(gender) |>
summarize(
across(
A1:A5,
\(x) mean(x, na.rm = TRUE)
)
)
```
What if we wanted to include the standard deviation as well? We can pass a `list` of functions into `across()`
```{r}
dat_bfi |>
group_by(gender) |>
summarize(
across(
A1:A5,
list(
mean = \(x) mean(x, na.rm = TRUE),
sd = \(x) sd(x, na.rm = TRUE)
)
)
)
```
## Complex `recoding` plus `across()`
Now sometimes with our scales we may encounter variables that are reverse scored.
```{r}
dat_bfi |>
mutate(
A1r = recode(
A1,
"6" = 1, "5" = 2, "4" = 3, "3" = 4, "2" = 5, "1" = 6
)
) |>
select(A1, A1r) |>
head()
# or
dat_bfi |>
mutate(A1r = max(A1, na.rm = TRUE) - A1 + min(A1, na.rm = TRUE)) |>
select(A1, A1r) |>
head()
```
However, we can implement some more complex code that will reverse `recode()` in one fell swoop!
We start with either specifying our columns that need reverse coding or get it from a data dictionary:
```{r}
reversed <- c("A1", "C4", "C5", "E1", "E2", "O2", "O5")
# or
dict <- psychTools::bfi.dictionary |>
as_tibble(rownames = "item")
reversed <- dict |>
filter(Keying == -1) |>
pull(item)
```
Putting it all together:
```{r}
dat_bfi |>
mutate(across(
all_of(reversed),
\(x) recode(x, "6" = 1, "5" = 2, "4" = 3, "3" = 4, "2" = 5, "1" = 6),
.names = "{.col}r"
)) |>
head()
```
The `.names` argument tells how to name the new columns.
If you omit `.names`, the columns will be modified in place.
In `.names`, the `{.col}` bit means "the column name",
and any text around that (here the letter `r`) is added to the name.
## `rowwise()`
`rowwise()` is a special `group_by()`.
It tells R to treat each row of a data frame as its own group.
`rowwise()` is useful for computing summary scores across items for each person.
For example, to compute total scores for each person in the `dat_bfi` data:
```{r}
dat_bfi |>
rowwise() |>
mutate(
.id = .id,
A_total = mean(c_across(A1:A5), na.rm = TRUE),
C_total = mean(c_across(C1:C5), na.rm = TRUE),
E_total = mean(c_across(E1:E5), na.rm = TRUE),
N_total = mean(c_across(N1:N5), na.rm = TRUE),
O_total = mean(c_across(O1:O5), na.rm = TRUE),
.before = everything()
) |>
head()
```
The `c_across()` function combines `c()` and `across()` into one.
It is like `c()` and creates a vector ala `c(1, 3, 5, 7)`,
but you can use the same options for selecting column names as `select()`.
The `.before` argument says where to put the new columns you `mutate()`.
`everything()` means "all the columns have I haven't named yet",
so `.before = everything()` means put the new columns at the beginning of the data frame.