How to add formula in a function?

This topic has been discussed here:

You should include your code i a reprex to make it easier for us to help you.

A prose description isn't sufficient, you also need to make a simple reprex that:

  1. Builds the input data you are using.
  2. The function you are trying to write, even if it doesn't work.
  3. Usage of the function you are trying to write, even if it doesn't work.
  4. Builds the output data you want the function to produce.

You can learn more about reprex's here:

https://www.jessemaegan.com/post/so-you-ve-been-asked-to-make-a-reprex/

Right now the is an issue with the version of reprex that is in CRAN so you should download it directly from github.

Until CRAN catches up with the latest version install reprex with

devtools::install_github("tidyverse/reprex")

You can't do what you want without using a package... unless you recreate some code from the implementation of the tidyverse from scratch yourself. Some of that code is in C not R. You can see it on github in tidyverse/

This is an example that shows the basics of how to do what you want using the tidyverse/rlang.

suppressPackageStartupMessages(library(tidyverse))
weights <- c(A = 2, B= 1, C = 9, H = 5)

mw3 <- function(S) {
    qs <- rlang::enquo(S)
    s <- rlang::expr_text(qs[[2]])
    sum(1:str_length(s) %>% map_dbl(~ weights[[str_sub(s, ., .)]]))
}

mw3(ACHHB)
#> [1] 22

Created on 2018-03-10 by the reprex package (v0.2.0).

1 Like