Add random factors to a data structure

add_random(.data = NULL, ..., .nested_in = NULL)

Arguments

.data

the data frame

...

the new random factor column name and the number of values of the random factor (if crossed) or the n per group (if nested); can be a vector of n per group if nested

.nested_in

the column(s) to nest in (if NULL, the factor is crossed with all columns)

Value

a data frame

Examples

# start a data frame
data1 <- add_random(school = 3)
# nest classes in schools (2 classes per school)
data2 <- add_random(data1, class = 2, .nested_in = "school")
# nest pupils in each class (different n per class)
data3 <- add_random(data2, pupil = c(20, 24, 23, 21, 25, 24), .nested_in = "class")
# cross each pupil with 10 questions
data4 <- add_random(data3, question = 10)

# compare nesting in 2 different factors
data <- add_random(A = 2, B = 2)
add_random(data, C = 2, .nested_in = "A")
#> # A tibble: 8 × 3
#>   A     B     C    
#>   <chr> <chr> <chr>
#> 1 A1    B1    C1   
#> 2 A1    B1    C2   
#> 3 A1    B2    C1   
#> 4 A1    B2    C2   
#> 5 A2    B1    C3   
#> 6 A2    B1    C4   
#> 7 A2    B2    C3   
#> 8 A2    B2    C4   
add_random(data, C = 2, .nested_in = "B")
#> # A tibble: 8 × 3
#>   A     B     C    
#>   <chr> <chr> <chr>
#> 1 A1    B1    C1   
#> 2 A1    B1    C2   
#> 3 A1    B2    C3   
#> 4 A1    B2    C4   
#> 5 A2    B1    C1   
#> 6 A2    B1    C2   
#> 7 A2    B2    C3   
#> 8 A2    B2    C4   

# specify item names
add_random(school = c("Hyndland Primary", "Hyndland Secondary")) %>%
  add_random(class = list(paste0("P", 1:7),
                          paste0("S", 1:6)),
             .nested_in = "school")
#> # A tibble: 13 × 2
#>    school             class
#>    <chr>              <chr>
#>  1 Hyndland Primary   P1   
#>  2 Hyndland Primary   P2   
#>  3 Hyndland Primary   P3   
#>  4 Hyndland Primary   P4   
#>  5 Hyndland Primary   P5   
#>  6 Hyndland Primary   P6   
#>  7 Hyndland Primary   P7   
#>  8 Hyndland Secondary S1   
#>  9 Hyndland Secondary S2   
#> 10 Hyndland Secondary S3   
#> 11 Hyndland Secondary S4   
#> 12 Hyndland Secondary S5   
#> 13 Hyndland Secondary S6