Also, for ANOVAs with a within-subjects variable, there must be an identifier column. In this case, it is subject. This identifier variable must be a factor. If it is a numeric type, the function will interpret it incorrectly and it won’t work properly.

library(tidyr)# This is what the original (wide) data looks like
# subject sex age before after
# 1 F old 9.5 7.1
# 2 M old 10.3 11.0
# 3 M old 7.5 5.8
# Convert it to long format
data_long<-gather(data,time,value,before:after)# Look at first few rows
head(data_long)#> subject sex age time value
#> 1 1 F old before 9.5
#> 2 2 M old before 10.3
#> 3 3 M old before 7.5
#> 4 4 F old before 12.4
#> 5 5 M old before 10.2
#> 6 6 M old before 11.0
# Make sure subject column is a factor
data_long$subject<-factor(data_long$subject)

One-way within ANOVA

First, convert the data to long format and make sure subject is a factor, as shown above. If subject is a numeric column, and not a factor, your results will be wrong!

More ANOVAs with within-subjects variables

These examples don’t operate on the data above, but they should illustrate how to do things.
First, convert the data to long format and make sure subject is a factor, as shown above.

# Two within variables
aov.ww<-aov(y~w1*w2+Error(subject/(w1*w2)),data=data_long)# One between variable and two within variables
aov.bww<-aov(y~b1*w1*w2+Error(subject/(w1*w2))+b1,data=data_long)# Two between variables and one within variables
aov.bww<-aov(y~b1*b2*w1+Error(subject/(w1))+b1*b2,data=data_long)