Datei > Neue Datei > R Markdown...
eine neue R
Markdown Datei erstellen. Den Text unter dem Setup Chunk (ab
Zeile 11) können Sie löschen. Unter
diesem Link können Sie auch unsere Vorlage-Datei herunterladen
(Rechtsklick > Speichern unter…).Da es sich um eine praktische Übung handelt, können wir Ihnen nicht alle neuen Befehle einzeln vorstellen. Stattdessen finden Sie hier Verweise auf sinnvolle Ressourcen, in denen Sie für die Bearbeitung unserer Aufgaben nachschlagen können.
Ressource | Beschreibung |
---|---|
Field, Kapitel 16 | Buchkapitel, das Schritt für Schritt erklärt, worum es geht, und wie man Multivariate Varianzanalysen in R durchführt. Große Empfehlung! |
Hinweis: Der Tipp ist diese Woche etwas länger.
Normalerweise müssen Sie ein Paket mit library()
laden,
damit Sie Funktionen aus diesem Paket nutzen können. Wenn Sie eine
Funktion aber nur sehr selten benötigen, können Sie einen Trick
verwenden, nämlich den doppelten Doppelpunkt ::
. Das
funktioniert nach dem Schema package::function()
und wird
von uns auch benutzt, um Funktionen mit häufigen Namen richtig
einzusetzen.
Wenn Sie diese Schreibweise verwenden, muss das jeweilige Paket nicht
geladen sein. Beispiel: psych::describe()
. Das Paket muss
allerdings installiert sein, damit diese Schreibweise funktioniert.
%>%
Die Pipe kommt aus dem Paket magrittr
und wird im
tidyverse
häufig verwendet. Sie kennen die Pipe vor allem
aus dplyr
, aber wenn Sie magrittr
oder
dplyr
geladen haben (d.h. mit library()
aktiviert), dann können Sie die Pipe für fast alle Befehle in R
benutzen, wenn Sie möchten. Das funktioniert so:
Der Code, der auf der linken Seite der Pipe steht, wird von
R “unter der Haube” auf der rechten Seite der Pipe eingesetzt,
und zwar standardmäßig immer als erstes Argument einer
Funktion, so dass andere Argumente der Funktion mit einem Komma
dahinter gestellt werden. Wenn Sie den Code auf der linken Seite der
Pipe an eine andere Stelle auf der rechten Seite der Funktion einsetzen
möchten, dann können Sie R mit einem Punkt .
sagen, wo der
Code der linken Seite eingesetzt werden soll (siehe Beispiel 4).
Nehmen wir mal an, wir wollen nur VP über 18 auswählen.
# ohne Pipe
dplyr::filter(example_data, age > 18)
# mit Pipe
example_data %>% dplyr::filter(age > 18)
Das ist besonders nützlich, wenn Befehle verschachtelt sind. Nehmen wir mal an, wir wollen nur VP über 18 auswählen und uns nur die Gruppe und unsere abhängige Variable anzeigen lassen.
# ohne Pipe
dplyr::select(dplyr::filter(example_data, age > 18), group, dependent_variable)
# mit Pipe
example_data %>%
dplyr::filter(age > 18) %>%
dplyr::select(group, dependent_variable)
Das funktioniert für fast alle Funktionen. Hinweis:
na.rm = TRUE
sorgt dafür, dass Missing Values bei der
Berechnung des Mittelwerts weggelassen werden.
# ohne Pipe
mean(age, na.rm = TRUE)
# mit Pipe
age %>% mean(na.rm = TRUE)
# ohne Pipe
lm(dependent_variable ~ group, data = example_data)
# mit Pipe
example_data %>% lm(dependent_variable ~ group, data = .)
Hinweis: Screenshot aus Field, Miles & Field (2012). Für fast alle Verfahren finden Sie in diesem Lehrbuch ähnliche Übersichten. Diese sind sehr wertvoll für die Prüfungsvorbereitung und darüber hinaus.
ocd_data.dat
über den Link https://md.psych.bio.uni-goettingen.de/mv/data/div/ocd_data.dat
in R ein.group
in
ocd_data
als Faktor mit sinnvoller Baseline. Geben Sie der
Gruppe “No Treatment Control” das Label “NT”.Unser Beispieldatensatz enthält hypothetische Daten zur Evaluation von Therapieprogrammen bei Zwangsstörungen.
Variable | Beschreibung |
---|---|
group | Faktor, der angibt, welche Art von Therapie die Versuchsperson erhalten hat. NT = Keine Therapie, BT = Verhaltenstherapie, CBT = Kognitive Verhaltenstherapie |
actions | Häufigkeit von Zwangshandlungen nach der Behandlung |
thoughts | Häufigkeit von Zwangsgedanken nach der Behandlung |
facet_wrap()
, um den Plot aus
Aufgabe 2.2 nach Gruppen getrennt darzustellen.ocd_data %>% dplyr::select(actions, thoughts) %>% by(ocd_data$group, cov)
,
um sich die Varianz-Kovarianz-Matrizen für jede Gruppe anzeigen zu
lassen.ocd_data %>% by(ocd_data$group, psych::describe)
, um
sich für jede Gruppe deskriptive Daten ausgeben zu lassen. Können Sie
den Befehl verstehen? Falls Sie eine Fehlermeldung bekommen,
installieren Sie das Paket psych
.mvnormtest
.boxM()
aus der library(heplots)
durch, um diese Voraussetzung zu
überprüfen. Können wir von Gleichheit der Varianz-Covarianz-Matrizen
ausgehen? Falls Sie eine Fehlermeldung bekommen, installieren
Sie das Paket heplots
.# Daten vorbereiten
nt <- ocd_data %>% dplyr::filter(group == "NT") %>% dplyr::select(2:3) %>% t()
bt <- ocd_data %>% dplyr::filter(group == "BT") %>% dplyr::select(2:3) %>% t()
cbt <- ocd_data %>% dplyr::filter(group == "CBT") %>% dplyr::select(2:3) %>% t()
# Tests durchführen
mvnormtest::mshapiro.test(nt)
mvnormtest::mshapiro.test(bt)
mvnormtest::mshapiro.test(cbt)
MANOVAS können in R mit dem Befehl manova()
durchgeführt
werden. Dieser Befehl funktioniert genau so wie lm()
und
aov()
in der Form:
manova(outcome ~ predictor, data = data)
. Der Unterschied
ist, dass im Vorfeld alle verwendeten Outcome-Variablen mit dem
cbind()
-Befehl zu einem Objekt “zusammengeschnürt”
werden.
BT
zur Referenzgruppe und wir würden den Unterschied, auch der Gruppe
CBT
als Effekt prüfen.ocd_data$thoughts
und ocd_data$actions
mit
Hilfe von cbind()
verbinden.manova()
, um die Analyse
durchzuführen. Speichern Sie das Ergebnis in einem Objekt.summary()
mit dem zusätzlichen Argument intercept = TRUE
an.summary.aov()
auf ihr
MANOVA-Modell an.Lassen Sie die Datei mit Strg
+ Shift
+
K
(Windows) oder Cmd
+ Shift
+
K
(Mac) rendern. Sie sollten nun im “Viewer” unten rechts
eine “schön aufpolierte” Version ihrer Datei sehen. Falls das klappt:
Herzlichen Glückwunsch! Ihr Code kann vollständig ohne Fehlermeldung
gerendert werden. Falls nicht: Nur mut, das wird schon noch! Gehen Sie
auf Fehlersuche! Ansonsten schaffen wir es ja in der Übung vielleicht
gemeinsam.
Anmerkung: Diese Übungszettel basieren zum Teil auf Aufgaben aus dem Lehrbuch Dicovering Statistics Using R (Field, Miles & Field, 2012). Sie wurden für den Zweck dieser Übung modifiziert, und der verwendete R-Code wurde aktualisiert.
Field, A., Miles, J., & Field, Z. (2012). Discovering Statistics Using R. London: SAGE Publications Ltd.
File > New file > R Markdown...
.
You can delete the text beneath Setup Chunk (starting from line
11). Alternatively, you can download our template file unter this
link (right click > save as…).Since this is a hands-on seminar, we won’t be able to present each and every new command to you explicitly. Instead, you’ll find here references to helpful ressources that you can use for completing this sheets.
Ressource | Description |
---|---|
Field, chapter 16 | Book chapter explaining step by step the why and how of multivariate analyses of variance in R. Highly recommended! |
Note: This week’s hint will be a bit longer than usual.
Usually, you’ll have to load a package using library()
in order to use functions from that package. However, there’s a trick
for when you’ll only need a function sporadically: Adding the package
name in front of the function using a double colon like this:
package::function()
. This also helps in using a function
with a name that occurs in multiple packages. E.g., you might have
noticed the warning dplyr::filter() masks stats::filter()
when loading the tidyverse. Here, dplyr::filter()
alone
will use the dplyr-command. If you want to use the filter-function from
the stats-commands, you can do so by typing
stats::filter()
.
The relevant packages don’t need to be loaded for this to work. However, they have to be installed on your computer.
%>%
Originally, the pipe stems from the package magrittr
and
is used frequently in the tidyverse
. You mostly know piping
from dplyr
, but as long as you have loaded either
magrittr
or dplyr
(using the
library()
-function), you’ll be able to use the pipe for
almost all R commands - if that is something you want to do. It works
like this:
R inserts the code on the left hand side of the pipe “under
the hood” into the right hand side of the pipe, the default
being using it as the first argument of a function. This way you can add
additional arguments with a comma behind it. If you want the left code
to be inserted at a different location, you can use the dot
.
to tell R where to put it (see example no. 4).
Say you only want to include subjects older than 18.
# without pipe
dplyr::filter(example_data, age > 18)
# with pipe
example_data %>% dplyr::filter(age > 18)
This is most useful when you have nested commands. Here, we only want to include subjects older than 18, and only look at the group vairable and our dependend variable.
# without pipe
dplyr::select(dplyr::filter(example_data, age > 18), group, dependent_variable)
# with pipe
example_data %>%
dplyr::filter(age > 18) %>%
dplyr::select(group, dependent_variable)
This works for almost all functions. Note: na.rm = TRUE
excludes missing values when calculating the mean.
# without pipe
mean(age, na.rm = TRUE)
# with pipe
age %>% mean(na.rm = TRUE)
# without pipe
lm(dependent_variable ~ group, data = example_data)
# with pipe
example_data %>% lm(dependent_variable ~ group, data = .)
Note: Screenshot from Field, Miles & Field (2012). There are summarys like this for almost all statistical procedures covered in this seminar. They’re invaluable for preparing for our exam and for life beyond this seminar.
ocd_data.dat
from the link https://md.psych.bio.uni-goettingen.de/mv/data/div/ocd_data.dat
into Rgroup
variable as a factor with a reasonable
baseline. Give the “No Treatment Control” group the lavel “NT”.Our data example contains hypothetical data of an evaluation study on different therapies for obsessive compulsive disorder
Variable | Meaning |
---|---|
group | Factor specifying the therapy method: NT = No Treatment, BT = behavioral therapy, CBT = cognitive behavioral therapy |
actions | Frequency of obsessive actions after the therapy |
thoughts | Frequency of obsessive thoughts after the therapy |
facet_wrap()
to show the plot from 2.2
separatly for each group.ocd_data %>% dplyr::select(actions, thoughts) %>% by(ocd_data$group, cov)
to get separate variance-covariance-matrices for each group.ocd_data %>% by(ocd_data$group, psych::describe)
to get
descriptive statistics for each group. Are you able to understand this
command? If you get an error message, you might have to install
the package psych
.mvnormtest
.boxM()
of library(heplots)
to
check that. Do we violate this assumtion? If you get an error
message, you might have to install the package
heplots
.# prepare data
nt <- ocd_data %>% dplyr::filter(group == "NT") %>% dplyr::select(2:3) %>% t()
bt <- ocd_data %>% dplyr::filter(group == "BT") %>% dplyr::select(2:3) %>% t()
cbt <- ocd_data %>% dplyr::group == "CBT") %>% dplyr::select(2:3) %>% t()
# run the tests
mvnormtest::mshapiro.test(nt)
mvnormtest::mshapiro.test(bt)
mvnormtest::mshapiro.test(cbt)
res.boxm <- heplots::boxM(ocd_data[,c('actions', 'thoughts')], group=ocd_data$group)
res.boxm
##
## Box's M-test for Homogeneity of Covariance Matrices
##
## data: ocd_data[, c("actions", "thoughts")]
## Chi-Sq (approx.) = 8.8932, df = 6, p-value = 0.1797
# summary(res.boxm) # for details
The p-value of our BoxM-test is not below 0.05, therefore we stay with H0 and state, that the variance-covariance-matrices don’t differ significantly.
You can run a MANOVA in R using the command manova()
.
This works exactly like the lm()
and aov()
commands you already know, the pattern being
manova(outcome ~ predictor, data = data)
. The difference,
however, is that you have to bind together all relevant outcome
variables beforehand, using the cbind()
command.
BT
as reference group and the difference to
group CBT
would be one of our effects.outcome
object by using
cbind()
to join ocd_data$thoughts
and
ocd_data$actions
together.manova()
command to run the analysis. Save the
result as an object.summary()
command on the MANOVA object,
including the additional argument intercept = TRUE
.summary.aov()
on the MANOVA model.Render this file using Ctrl
+ Shift
+
K
(Windows) or Cmd
+ Shift
+
K
(Mac). In the viewer you should see a pretty versionn of
your file. If this works: Congratulations! Your code can be rendered
completely and without error codes! If it doesn’t: No worries, you’ll
get there! Go hunting for errors in your code! Otherwise, we’ll get it
to render in the next seminar session!
Note: These sheets are based partially on exercises from the book Dicovering Statistics Using R (Field, Miles & Field, 2012). They’ve been modified for the porpuses of this seminar, and the R code was updated.
Field, A., Miles, J., & Field, Z. (2012). Discovering Statistics Using R. London: SAGE Publications Ltd.