Reputation: 1946
My data involves an experiment with a dependent variable (DV) collected over several conditions and is structured as follows:
AnalysedData <- data.frame(Participant = c("Bill", "Bill", "Bill", "Harry", "Harry", "Harry", "Paul", "Paul", "Paul"),
Code = c(1, 1, 1, 2, 2, 2, 1, 1, 1),
Condition = c("Con", "Expr", "Plac", "Con", "Expr", "Plac", "Con", "Expr", "Plac"),
DV = c(26.07, 26.06, 26.05, 26.09, 26.04, 26.65, 26.64, 26.62, 26.63))
All the participants received the same conditions but completed two of the conditions in a randomised order - the control condition was always conducted first. Those who completed the experimental (Expr
) condition as their second trial have a 1 for Code
whilst those who completed the placebo (Plac
) as their second trial have a 2 for Code
.
I wish to include a new column AnalysedData$Trial
whereby the order of trials, for each participant, are included. My preferred output would be:
AnalysedData <- data.frame(Participant = c("Bill", "Bill", "Bill", "Harry", "Harry", "Harry", "Paul", "Paul", "Paul"),
Code = c(1, 1, 1, 2, 2, 2, 1, 1, 1),
Condition = c("Con", "Expr", "Plac", "Con", "Expr", "Plac", "Con", "Expr", "Plac"),
DV = c(26.07, 26.06, 26.05, 26.09, 26.04, 26.65, 26.64, 26.62, 26.63),
Trial = c(1, 2, 3, 1, 3, 2, 1, 2, 3))
The preferred output address that Harry completed the placebo condition second and the experimental condition third, giving him c(1, 3, 2)
. In contrast, Bill and Paul both complete the experimental condition second and the placebo condition third, giving c(1, 2, 3)
. As per above, this alternate sequence is indicated by Code
equalling 1 for Bill and Paul, 2 for Harry.
I know that I can include a 1 to designate the first trial completed (Con
for all participants) using the following:
AnalysedData$Trial <- ifelse(AnalysedData$Condition == "Con", 1, 0)
How do I complete the above for multiple conditions?
Upvotes: 1
Views: 134
Reputation: 341
This should work:
AnalysedData$Trial <- ifelse(AnalysedData$Condition == "Con", 1, 0)
index<-AnalysedData$Condition == "Plac"
AnalysedData$Trial[index]<-rep(2,sum(index))
Upvotes: 0
Reputation: 83235
With a combination of ifelse
, as.integer
(or as.numeric
) and factor
you can make use of the fact that factor variables are stored as integers with labels:
AnalysedData$Trial <- ifelse(AnalysedData$Code==1,
as.integer(factor(AnalysedData$Condition,
levels = c("Con", "Expr", "Plac"))),
as.integer(factor(AnalysedData$Condition,
levels = c("Con", "Plac", "Expr"))))
you get:
> AnalysedData
Participant Code Condition DV Trial
1 Bill 1 Con 26.07 1
2 Bill 1 Expr 26.06 2
3 Bill 1 Plac 26.05 3
4 Harry 2 Con 26.09 1
5 Harry 2 Expr 26.04 3
6 Harry 2 Plac 26.65 2
7 Paul 1 Con 26.64 1
8 Paul 1 Expr 26.62 2
9 Paul 1 Plac 26.63 3
Upvotes: 1