Skip to contents

Simulate a vector of random factor values. Provides the option of inserting base::NA or returning base::NULL or zero-length factors.

Usage

sim_factor(
  x = factor(month.name),
  length = c(1, 10),
  prob_na = 0,
  n_na = 1L,
  prob_null = 0,
  prob_zero_length = 0,
  names = FALSE,
  replace = TRUE
)

Arguments

x

(factor)
The vector to randomly sample from.

length

(integer vector of length 1 or 2)
The number of elements in the simulated vector. If length(length)==1L, sets the number of elements to length. If length(length)==2L, randomly selects the number of elements from the interval [min, max].

prob_na

(Scalar numeric: [0, 1])
The probability of inserting an NA.

n_na

(Scalar integer: [0, Inf])
The number of NAs to insert.

prob_null

(Scalar numeric: [0, 1])
The probability of returning a NULL object.

prob_zero_length

(Scalar numeric: [0, 1])
The probability of returning a zero-length vector.

names

(Scalar logical: c(TRUE, FALSE))
Whether or not the vector should have names. TRUE (default) sets names as name_1, name_2, name_3, ...

replace

(Scalar logical: c(TRUE, FALSE))
Whether or not elements from x can be repeated in the result. TRUE (default) samples with replacement.

Value

factor

Examples

#----------------------------------------------------------------------------
# sim_factor() examples
#----------------------------------------------------------------------------
library(bkcheck)

sim_factor()
#> [1] February April   
#> 12 Levels: April August December February January July June March ... September
sim_factor(prob_na = 1)
#> [1] <NA>
#> 12 Levels: April August December February January July June March ... September
sim_factor(prob_null = 1)
#> NULL
sim_factor(prob_zero_length = 1)
#> factor()
#> Levels: 
sim_factor(names = TRUE)
#>    name_1    name_2    name_3    name_4    name_5    name_6    name_7    name_8 
#>   October  February September  December  December   January      June September 
#>    name_9 
#>  December 
#> 12 Levels: April August December February January July June March ... September

sim_factor(factor(rand_chars(10)), replace = FALSE)
#>  [1] Sn^1oK  f(%$"!  u+tQ,W  i|.|&+  #y%}*s  DUJnTG  1#Yc!y  Mu*9.I  lAa5x\\
#> [10] kkE4}b 
#> 10 Levels: #y%}*s 1#Yc!y DUJnTG Mu*9.I Sn^1oK f(%$"! i|.|&+ kkE4}b ... u+tQ,W
sim_factor(factor(rand_chars(10)), replace = TRUE)
#> [1] d)(!V+ ynvbNW fwBq4[ ri73gl
#> 10 Levels: 7_OM}Y Bmv&IH P!S'Vz Rc%gfC TT^nbq d)(!V+ fwBq4[ jHoylq ... ynvbNW