|
| 1 | +#' create columns with random numbers |
| 2 | +#' |
| 3 | +#' For demonstration purposes, add the specified number of |
| 4 | +#' random columns to a model matrix. This is intended to be used |
| 5 | +#' in modeling functions, e.g. `model_train()`, `lm()`, and so on |
| 6 | +#' to explore the extent to which random columns "explain" the |
| 7 | +#' response variable. |
| 8 | +#' |
| 9 | +#' @param df How many columns to add |
| 10 | +#' @param rdist Function to generate each column's numbers (default: `rnorm`) |
| 11 | +#' @param args A list holding the parameters (if any) to be used for the `rdist` argument |
| 12 | +#' @param n OPTIONALLY, dictate the number of rows in the output |
| 13 | +#' @param seed Integer seed for the random-number generator |
| 14 | +#' |
| 15 | +#' @details `random_terms()` will try to guess a suitable value for `n` based on |
| 16 | +#' the calling function. |
| 17 | +#' |
| 18 | +#' @examples |
| 19 | +#' mtcars |> model_train(mpg ~ wt + random_terms(4)) |> conf_interval() |
| 20 | +#' mtcars |> model_train(mpg ~ wt + random_terms(4)) |> anova_report() |
| 21 | +#' # must state number of rows if not part of a modeling tilde expression |
| 22 | +#' goo <- mtcars |> bind_cols(r = random_terms(3)) |
| 23 | +#' @export |
| 24 | +random_terms<-function (df=1,rdist=rnorm,args=list(),n,seed=NULL) |
| 25 | +{ |
| 26 | +if (missing(n)) { |
| 27 | +arg<- sys.call(1)[[2]] |
| 28 | +# walk down the stack until reaching the first argument to this function |
| 29 | +while(length(arg)>1)arg<-arg[[2]] |
| 30 | +# if it's a data frame, we have our answer. |
| 31 | +if (inherits(eval(arg),"data.frame"))n= nrow(eval(arg)) |
| 32 | +else stop("Need to specify argument <n> in random_terms().") |
| 33 | + } |
| 34 | +if (!is.null(seed)) { |
| 35 | + set.seed(seed) |
| 36 | + } |
| 37 | +result<-matrix(do.call(rdist,args= c(list(n=df*n), |
| 38 | +args)),nrow=n) |
| 39 | +return(result) |
| 40 | +} |