set.seed(1234)
# To create a "scalar" `rvar_factor`, pass a one-dimensional array or a vector
# whose length (here `4000`) is the desired number of draws:
x <- rvar(sample(c("a","a","a","b","c"), 4000, replace = TRUE))
x
# Create random vectors by adding an additional dimension:
x_array <- array(c(
sample(c("a","a","a","b","c"), 4000, replace = TRUE),
sample(c("a","a","b","c","c"), 4000, replace = TRUE),
sample(c("b","b","b","b","c"), 4000, replace = TRUE),
sample(c("d","d","b","b","c"), 4000, replace = TRUE)
), dim = c(4000, 4))
rvar_factor(x_array)
# You can also create ordered factors
rvar_ordered(x_array)
# arguments of factor() and ordered() are passed down by the constructor
# e.g. we can reorder levels of an ordered factor:
rvar_ordered(x_array, levels = c("d","c","b","a"))
# Unlike base factors, rvar factors can be matrices or arrays:
rvar_factor(x_array, dim = c(2, 2))
# If the input to rvar_factor() is an array with a `"levels"` attribute, it
# will use those as the levels of the factor
y_array <- t(array(rbinom(3000, 1, c(0.1, 0.5, 0.9)) + 1, dim = c(3, 1000)))
rvar(y_array)
# with levels
attr(y_array, "levels") = c("a", "b")
rvar_factor(y_array)
Run the code above in your browser using DataLab