I imagine there are many ways to do this that depend on the larger structure of your data. But here's one approach that works if you supply the complete character string to count as well as a named vector of letters you want counts for.
If you include a little more detail about your input data structure or your expected output, someone might be able to help even more.
Hope this helps!
library(tidyverse)
count_chr <- function(input_chr, input_let){
lengths(str_extract_all(input_chr, input_let))
}
my_string <- "HHCCCNNNOOO"
my_letters <- c("H" = "H", "C" = "C", "N" = "N", "O" = "O")
map_df(my_letters, count_chr, input_chr = my_string) %>%
gather(letter, count)
#> # A tibble: 4 x 2
#> letter count
#> <chr> <int>
#> 1 H 2
#> 2 C 3
#> 3 N 3
#> 4 O 3