File: standardize_data.Rmd

package info (click to toggle)
r-cran-datawizard 0.6.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,736 kB
  • sloc: sh: 13; makefile: 2
file content (452 lines) | stat: -rw-r--r-- 12,810 bytes parent folder | download | duplicates (2)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
---
title: "Data Standardization"
output: 
  rmarkdown::html_vignette:
    toc: true
    fig_width: 10.08
    fig_height: 6
vignette: >
  \usepackage[utf8]{inputenc}
  %\VignetteIndexEntry{Data Standardization}
  %\VignetteEngine{knitr::rmarkdown}
---

```{r message=FALSE, warning=FALSE, include=FALSE}
options(knitr.kable.NA = "")
knitr::opts_chunk$set(
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  dpi = 300
)

pkgs <- c(
  "datawizard",
  "poorman",
  "see",
  "ggplot2",
  "parameters",
  "lme4"
)

if (!all(sapply(pkgs, requireNamespace, quietly = TRUE))) {
  knitr::opts_chunk$set(eval = FALSE)
}
```

This vignette can be referred to by citing the following:

> Patil et al., (2022). datawizard: An R Package for Easy Data Preparation and Statistical Transformations. *Journal of Open Source Software*, *7*(78), 4684, https://doi.org/10.21105/joss.04684

# Introduction

To make sense of their data and effects, scientists might want to standardize
(Z-score) their variables. This makes the data unitless, expressed only in terms
of deviation from an index of centrality (e.g., the mean or the median).
However, aside from some benefits, standardization also comes with challenges
and issues, that the scientist should be aware of.

## Methods of Standardization

The `datawizard` package offers two methods of standardization via the
`standardize()` function:

- **Normal standardization**: center around the *mean*, with *SD* units
  (default).

- **Robust standardization**: center around the *median*, with *MAD* (median
  absolute deviation) units (`robust = TRUE`).

Let's look at the following example:

```{r}
library(datawizard)
library(effectsize) # for data

# let's have a look at what the data look like
data("hardlyworking", package = "effectsize")
head(hardlyworking)

# let's use both methods of standardization
hardlyworking$xtra_hours_z <- standardize(hardlyworking$xtra_hours)
hardlyworking$xtra_hours_zr <- standardize(hardlyworking$xtra_hours, robust = TRUE)
```

We can see that different methods give different central and variation values:

```{r, eval=FALSE}
library(dplyr)

hardlyworking %>%
  select(starts_with("xtra_hours")) %>%
  data_to_long() %>%
  group_by(Name) %>%
  summarise(
    mean = mean(Value),
    sd = sd(Value),
    median = median(Value),
    mad = mad(Value)
  )
```

```{r, echo=FALSE}
library(poorman)

hardlyworking %>%
  select(starts_with("xtra_hours")) %>%
  reshape_longer(names_to = "name", values_to = "value") %>%
  group_by(name) %>%
  summarise(
    mean = mean(value),
    sd = sd(value),
    median = median(value),
    mad = mad(value)
  ) %>%
  knitr::kable(digits = 4)
```

`standardize()` can also be used to standardize a full data frame - where each
numeric variable is standardized separately:

```{r}
hardlyworking_z <- standardize(hardlyworking)
```

```{r, eval=FALSE}
hardlyworking_z %>%
  select(-xtra_hours_z, -xtra_hours_zr) %>%
  data_to_long() %>%
  group_by(Name) %>%
  summarise(
    mean = mean(Value),
    sd = sd(Value),
    median = median(Value),
    mad = mad(Value)
  )
```

```{r, echo=FALSE}
hardlyworking_z %>%
  select(-xtra_hours_z, -xtra_hours_zr) %>%
  reshape_longer(names_to = "name", values_to = "value") %>%
  group_by(name) %>%
  summarise(
    mean = mean(value),
    sd = sd(value),
    median = median(value),
    mad = mad(value)
  ) %>%
  knitr::kable(digits = 4)
```

Weighted standardization is also supported via the `weights` argument, and
factors can also be standardized (if you're into that kind of thing) by setting
`force = TRUE`, which converts factors to treatment-coded dummy variables before
standardizing.

## Variable-wise *vs.* Participant-wise 

Standardization is an important step and extra caution is required in
**repeated-measures designs**, in which there are three ways of standardizing
data:

- **Variable-wise**: The most common method. A simple scaling of each column.

- **Participant-wise**: Variables are standardized "within" each participant,
  *i.e.*, for each participant, by the participant's mean and SD.

- **Full**: Participant-wise first and then re-standardizing variable-wise.

Unfortunately, the method used is often not explicitly stated. This is an issue
as these methods can generate important discrepancies (that can in turn
contribute to the reproducibility crisis). Let's investigate these 3 methods.

### The Data

We will take the `emotion` dataset in which participants were exposed to
negative pictures and had to rate their emotions (**valence**) and the amount of
memories associated with the picture (**autobiographical link**). One could make
the hypothesis that for young participants with no context of war or violence,
the most negative pictures (mutilations) are less related to memories than less
negative pictures (involving for example car crashes or sick people). In other
words, **we expect a positive relationship between valence** (with high values
corresponding to less negativity) **and autobiographical link**.

Let's have a look at the data, averaged by participants:

```{r, eval=FALSE}
# Download the 'emotion' dataset
load(url("https://raw.githubusercontent.com/neuropsychology/psycho.R/master/data/emotion.rda"))

# Discard neutral pictures (keep only negative)
emotion <- emotion %>% filter(Emotion_Condition == "Negative")

# Summary
emotion %>%
  drop_na(Subjective_Valence, Autobiographical_Link) %>%
  group_by(Participant_ID) %>%
  summarise(
    n_Trials = n(),
    Valence_Mean = mean(Subjective_Valence),
    Valence_SD = sd(Subjective_Valence)
  )
```

```{r, echo=FALSE}
load(url("https://raw.githubusercontent.com/neuropsychology/psycho.R/master/data/emotion.rda"))

# Discard neutral pictures (keep only negative)
emotion <- emotion %>% filter(Emotion_Condition == "Negative")

# Summary
emotion %>%
  subset(!(is.na(Subjective_Valence) | is.na(Autobiographical_Link))) %>%
  group_by(Participant_ID) %>%
  summarise(
    n_Trials = n(),
    Valence_Mean = mean(Subjective_Valence),
    Valence_SD = sd(Subjective_Valence)
  )
```

As we can see from the means and SDs, there is a lot of variability **between**
participants both in their means and their individual *within*-participant SD.

### Effect of Standardization 

We will create three data frames standardized with each of the three
techniques.

```{r, warning=FALSE}
Z_VariableWise <- emotion %>%
  standardize()

Z_ParticipantWise <- emotion %>%
  group_by(Participant_ID) %>%
  standardize()

Z_Full <- emotion %>%
  group_by(Participant_ID) %>%
  standardize() %>%
  ungroup() %>%
  standardize()
```

Let's see how these three standardization techniques affected the **Valence**
variable.

### Across Participants

We can calculate the mean and SD of *Valence* across all participants:

```{r, eval=FALSE}
# Create a convenient function to print
summarise_Subjective_Valence <- function(data) {
  df_name <- deparse(substitute(data))
  data %>%
    ungroup() %>%
    summarise(
      DF = df_name,
      Mean = mean(Subjective_Valence),
      SD = sd(Subjective_Valence)
    )
}
# Check the results
rbind(
  summarise_Subjective_Valence(Z_VariableWise),
  summarise_Subjective_Valence(Z_ParticipantWise),
  summarise_Subjective_Valence(Z_Full)
)
```

```{r, echo=FALSE}
# Create a convenient function to print
summarise_Subjective_Valence <- function(data) {
  df_name <- deparse(substitute(data))
  data <- data %>%
    ungroup() %>%
    summarise(
      Mean = mean(Subjective_Valence),
      SD = sd(Subjective_Valence)
    )
  cbind(DF = df_name, data)
}
# Check the results
rbind(
  summarise_Subjective_Valence(Z_VariableWise),
  summarise_Subjective_Valence(Z_ParticipantWise),
  summarise_Subjective_Valence(Z_Full)
) %>%
  knitr::kable(digits = 2)
```


The **means** and the **SD** appear as fairly similar (0 and 1)...

```{r, fig.width=7, fig.height=4.5, results='markup', fig.align='center'}
library(see)
library(ggplot2)

ggplot() +
  geom_density(aes(Z_VariableWise$Subjective_Valence,
    color = "Z_VariableWise"
  ), linewidth = 1) +
  geom_density(aes(Z_ParticipantWise$Subjective_Valence,
    color = "Z_ParticipantWise"
  ), linewidth = 1) +
  geom_density(aes(Z_Full$Subjective_Valence,
    color = "Z_Full"
  ), linewidth = 1) +
  see::theme_modern() +
  labs(color = "")
```

and so do the marginal distributions...

### At the Participant Level

However, we can also look at what happens in the participant level. Let's look at
the first 5 participants:

```{r, eval=FALSE}
# Create convenient function
print_participants <- function(data) {
  df_name <- deparse(substitute(data))
  data %>%
    group_by(Participant_ID) %>%
    summarise(
      DF = df_name,
      Mean = mean(Subjective_Valence),
      SD = sd(Subjective_Valence)
    ) %>%
    head(5) %>%
    select(DF, everything())
}

# Check the results
rbind(
  print_participants(Z_VariableWise),
  print_participants(Z_ParticipantWise),
  print_participants(Z_Full)
)
```


```{r, echo=FALSE}
# Create convenient function
print_participants <- function(data) {
  df_name <- deparse(substitute(data))
  data %>%
    group_by(Participant_ID) %>%
    summarise(
      Mean = mean(Subjective_Valence),
      SD = sd(Subjective_Valence)
    ) %>%
    cbind(DF = df_name, .) %>%
    head(5) %>%
    select(DF, everything())
}

# Check the results
rbind(
  print_participants(Z_VariableWise),
  print_participants(Z_ParticipantWise),
  print_participants(Z_Full)
) %>%
  knitr::kable(digits = 2)
```

Seems like *full* and *participant-wise* standardization give similar results,
but different ones than *variable-wise* standardization.

### Compare

Let's do a **correlation** between the **variable-wise and participant-wise
methods**.

```{r, fig.width=7, fig.height=4.5, results='markup', fig.align='center'}
r <- cor.test(
  Z_VariableWise$Subjective_Valence,
  Z_ParticipantWise$Subjective_Valence
)

data.frame(
  Original = emotion$Subjective_Valence,
  VariableWise = Z_VariableWise$Subjective_Valence,
  ParticipantWise = Z_ParticipantWise$Subjective_Valence
) %>%
  ggplot(aes(x = VariableWise, y = ParticipantWise, colour = Original)) +
  geom_point(alpha = 0.75, shape = 16) +
  geom_smooth(method = "lm", color = "black") +
  scale_color_distiller(palette = 1) +
  ggtitle(paste0("r = ", round(r$estimate, 2))) +
  see::theme_modern()
```

While the three standardization methods roughly present the same characteristics
at a general level (mean 0 and SD 1) and a similar distribution, their values
are not exactly the same!

Let's now answer the original question by investigating the **linear relationship between valence and autobiographical link**. We can do this by
running a mixed-effects model with participants entered as random effects.

```{r}
library(lme4)
m_raw <- lmer(
  formula = Subjective_Valence ~ Autobiographical_Link + (1 | Participant_ID),
  data = emotion
)
m_VariableWise <- update(m_raw, data = Z_VariableWise)
m_ParticipantWise <- update(m_raw, data = Z_ParticipantWise)
m_Full <- update(m_raw, data = Z_Full)
```

We can extract the parameters of interest from each model, and find:

```{r}
# Convenient function
get_par <- function(model) {
  mod_name <- deparse(substitute(model))
  parameters::model_parameters(model) %>%
    mutate(Model = mod_name) %>%
    select(-Parameter) %>%
    select(Model, everything()) %>%
    .[-1, ]
}

# Run the model on all datasets
rbind(
  get_par(m_raw),
  get_par(m_VariableWise),
  get_par(m_ParticipantWise),
  get_par(m_Full)
)
```

As we can see, **variable-wise** standardization only affects **the coefficient** (which is expected, as it changes the unit), but not the test
statistic or statistical significance. However, using **participant-wise**
standardization *does* affect the coefficient **and** the significance. 

**No method is better or more justified, and the choice depends on the specific case, context, data and goal.**

### Conclusion

1. **Standardization can be useful in *some* cases and should be justified**.

2. **Variable and Participant-wise standardization methods *appear* to produce similar data**.

3. **Variable and Participant-wise standardization can lead to different results**.

4. **The chosen method can strongly influence the results and should therefore be explicitly stated and justified to enhance reproducibility of results**.

We showed here yet another way of **sneakily tweaking the data** that can change
the results. To prevent its use as a bad practice, we can only highlight the
importance of open data, open analysis/scripts, and preregistration.

# See also 

- `datawizard::demean()`: <https://easystats.github.io/datawizard/reference/demean.html>
- `standardize_parameters(method = "pseudo")` for mixed-effects models
<https://easystats.github.io/parameters/articles/standardize_parameters_effsize.html>

# References