knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()) # Set WD to Root
here::i_am("my_dev/formula.Rmd")
library(here)
usethis::use_r("formula")

Fn: Parse to Formula

#' Parse symbols to LHS and RHS of formula
#'
#' Most common use cases would be passing string to `lhr` and `rhs` of the formula.
#'
#'
#' @param fun Function that accept formula object as first argument
#' @param lhs (Quote or Unquoted) Expression for left-hand sided of the formula
#' @param rhs (Quote or Unquoted) Expression for right-hand sided of the formula
#' @param ... pass to `fun`
#'
#' @return object as return by `fun`
#' @export
#'
#' @examples
#' parse_to_formula(lm, "Sepal.Length", "Sepal.Width", data = iris)
parse_to_formula <- function(fun, lhs, rhs, ...) {

  lhs <- rlang::ensym(lhs)
  rhs <- rlang::ensym(rhs)
  fun <- rlang::ensym(fun)
  dot <- rlang::enexprs(...)

  eval(rlang::expr((!!fun)(!!lhs ~ !!rhs, !!!dot)))

}

lbmod::parse_to_formula(lm, "Sepal.Length", "Sepal.Width", data = iris)

Fn: Parse to formula (2 Sided) [New]

parse_to_formula_2s <- function(fun = "lm", lhs, rhs, 
                                args = list(), 
                                pkg = "stats") {

  lhs <- rlang::ensym(lhs)
  rhs <- rlang::ensym(rhs)
  form2 <- rlang::new_formula(lhs, rhs)
  call <- rlang::call2(fun, form2, .ns = pkg, !!!args)
  eval(call)

}

parse_to_formula_2s(fun = "lm", "Sepal.Length", "Species",
                    pkg = "stats", args = list(data = iris))
# lm(Sepal.Length ~ Species, data = iris)
test_pluck_formula <- function(a, b) {

  a <- rlang::ensym(a)
  b <- rlang::ensym(b)
  f <- rlang::new_formula(a, b)
  f
}

test_pluck_formula("c", "d")
rlang::new_formula(quote(a), quote(b))

rlang::new_formula(rlang::expr(a), quote(b))
rlang::new_formula(rlang::expr(a), quote(b))
rlang::new_formula("a", quote(b))

lm(rlang::new_formula(quote(Sepal.Length), quote(Species)), data = iris)

lm(rlang::new_formula(rlang::sym("Sepal.Length"), rlang::sym("Species")), 
   data = iris)

lm(Sepal.Length ~ Species, data = iris)


Lightbridge-KS/lbmod documentation built on Jan. 28, 2024, 6:21 p.m.