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 x 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 x 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