wants <- c("dplyr", "tidyr")
has <- wants %in% rownames(installed.packages())
if(any(!has)) install.packages(wants[!has])
Nj <- 2
P <- 2
Q <- 3
id <- 1:(P*Nj)
DV_t1 <- round(rnorm(P*Nj, -1, 1), 2)
DV_t2 <- round(rnorm(P*Nj, 0, 1), 2)
DV_t3 <- round(rnorm(P*Nj, 1, 1), 2)
IVbtw <- factor(rep(c("A", "B"), Nj))
(datW <- data.frame(id, IVbtw, DV_t1, DV_t2, DV_t3))
id IVbtw DV_t1 DV_t2 DV_t3
1 1 A -1.07 -0.47 2.38
2 2 B 0.85 1.39 0.45
3 3 A 0.14 1.85 2.53
4 4 B -1.79 -0.20 1.00
library(dplyr)
library(tidyr)
datL <- datW %>%
pivot_longer(cols=starts_with("DV_"),
names_to="time", values_to="DV",
names_prefix="DV_")
datL
# A tibble: 12 x 4
id IVbtw time DV
<int> <fct> <chr> <dbl>
1 1 A t1 -1.07
2 1 A t2 -0.47
3 1 A t3 2.38
4 2 B t1 0.85
5 2 B t2 1.39
6 2 B t3 0.45
7 3 A t1 0.14
8 3 A t2 1.85
9 3 A t3 2.53
10 4 B t1 -1.79
11 4 B t2 -0.2
12 4 B t3 1
One variable
# A tibble: 4 x 5
id IVbtw DV_t1 DV_t2 DV_t3
<int> <fct> <dbl> <dbl> <dbl>
1 1 A -1.07 -0.47 2.38
2 2 B 0.85 1.39 0.45
3 3 A 0.14 1.85 2.53
4 4 B -1.79 -0.2 1
Two variables
datL %>%
mutate(DVsq=DV^2) %>%
pivot_wider(id_cols=c(id, IVbtw),
names_from=time, values_from=c(DV, DVsq))
# A tibble: 4 x 8
id IVbtw DV_t1 DV_t2 DV_t3 DVsq_t1 DVsq_t2 DVsq_t3
<int> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 A -1.07 -0.47 2.38 1.14 0.221 5.66
2 2 B 0.85 1.39 0.45 0.722 1.93 0.202
3 3 A 0.14 1.85 2.53 0.0196 3.42 6.40
4 4 B -1.79 -0.2 1 3.20 0.04 1
R markdown - markdown - R code - all posts