Calculates a vector containing a unique phase number for every sequential occurrence of a phase or treatment condition. This is useful for creating a grouping variable to be used in calculating effect sizes for each pair of A-B phases within treatment reversal designs.

calc_phase_pairs(x, session = seq_along(x))

Arguments

x

vector of phase/condition labels.

session

numeric vector of measurement occasions, used to sort x before calculating phase pairs.

Value

A vector containing an integer phase number for every observation.

Examples

# Basic use-case
x <- rep(c("A","B","C","B","C","A","C"), c(4:10))
calc_phase_pairs(x)
#>  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
#> [39] 2 3 3 3 3 3 3 3 3 3 3

# Using session argument to handle sort order
session <- sample(seq_along(x))
x_scrambled <- x[session]
dat <- data.frame(
  x = x_scrambled,
  session = session,
  phase_pair = calc_phase_pairs(x_scrambled, session = session)
)
dat_sorted <- dat[order(session),]
identical(x, dat_sorted$x)
#> [1] TRUE

# With a grouped data.frame
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
Schmidt2007 %>%
  group_by(Behavior_type, Case_pseudonym) %>%
  mutate(phase_pair = calc_phase_pairs(Condition, session = Session_number))
#> # A tibble: 172 × 14
#> # Groups:   Behavior_type, Case_pseudonym [6]
#>    Behavior_type  Procedure Metric Session_length Interval_length Case_pseudonym
#>    <chr>          <chr>     <chr>           <int>           <int> <chr>         
#>  1 Disruptive Be… Event co… count              10              NA Faith         
#>  2 Disruptive Be… Event co… count              10              NA Faith         
#>  3 Disruptive Be… Event co… count              10              NA Faith         
#>  4 Disruptive Be… Event co… count              10              NA Faith         
#>  5 Disruptive Be… Event co… count              10              NA Faith         
#>  6 Disruptive Be… Event co… count              10              NA Faith         
#>  7 Disruptive Be… Event co… count              10              NA Faith         
#>  8 Disruptive Be… Event co… count              10              NA Faith         
#>  9 Disruptive Be… Event co… count              10              NA Faith         
#> 10 Disruptive Be… Event co… count              10              NA Faith         
#> # ℹ 162 more rows
#> # ℹ 8 more variables: Session_number <int>, Phase <chr>, Condition <chr>,
#> #   Outcome <dbl>, Phase_num <int>, direction <chr>, n_Intervals <dbl>,
#> #   phase_pair <int>