分別處理male & female,再做合併

data <- read.table("stateAnxiety.txt", header = T)
female <- data[,c(1:5)]
colnames(female) <- c("1","2","3","4","5")
fe.1 <- stack(female)
fe.1$sex <- "female"
fe.1$ID <- rep(1:50,5)

male <- data[,c(6:10)]
colnames(male) <- c("1","2","3","4","5")
ma.1 <- stack(male)
ma.1$sex <- "male"
ma.1$ID <- rep(1:50,5)
dta <- rbind(ma.1, fe.1)
str(dta)
## 'data.frame':    500 obs. of  4 variables:
##  $ values: int  6 4 17 19 12 11 14 9 12 11 ...
##  $ ind   : Factor w/ 5 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ sex   : chr  "male" "male" "male" "male" ...
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...

計算mean和se

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
dta.1 <- dta %>% group_by(ind, sex) %>%
  summarize(mean=mean(values), se=sd(values)/sqrt(n()))

繪出error bars

library(ggplot2)
p1 <- ggplot(data=dta.1) +
  aes(ind, mean, group=sex, shape=sex) +
  geom_errorbar(aes(ymin=mean - se,
                    ymax=mean + se),
                width=.3, size=.6, 
                position=position_dodge(.5)) +
  geom_line(position=position_dodge(.5), 
            aes(linetype=sex)) +
  geom_point(position=position_dodge(.5), 
             size=rel(2)) +
  scale_shape_manual(values = c(1, 7)) +
  labs(x="Week", y="Anxiety score")+
  theme(legend.position= c(0.07,0.9),)
  
p1

There is gender difference in state anxiety.

計算mean和se

dta.2 <- dta %>% group_by(ID, sex) %>%
  summarize(mean=mean(values), se=sd(values)/sqrt(n()))

繪出error bars

p2 <- ggplot(data=dta.2) +
  aes(ID, mean, group=sex, shape=sex) +
  geom_errorbar(aes(ymin=mean - se,
                    ymax=mean + se),
                width=.3, size=.6, 
                position=position_dodge(.5)) +
   geom_point(aes(shape = sex, color = sex), size = 3)+
  labs(x="ID", y="Anxiety score")+
  theme(legend.position= c(0.07,0.9),)+
  theme_bw()
  
p2

There are individual differences in state anxiety.