Calculate the sum of all the characters

Function should count how many H C N And O are there and then sum them up
I want to make a function in which i can calculate the sum of all the characters which I've already stored (eg.-H=1, C=12)
Input would be like

HHCCCNNNOOO

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
3 Likes

Whta is %>% this for?

am making a function in which it could calculate the total molecular weight of a protein. So, i have already entered or stored each molecular weights of every amino acids,

I want my function to read the argument or input like ABCDEF in this format. Please help me with this

Hi Pooja, the %>% is known as a "pipe operator". You can read more about them here:

Some people read a series of piped lines as "then". i.e. in the example shown above

map_df (arguement1, arguement2) "then"
gather(arguement1, arguement2)

am making a function in which it could calculate the total molecular weight of a protein. So, i have already entered or stored each molecular weights of every amino acids,

I want my function to read the argument or input like ABCDEF in this format. Please help me with this

@pooja,

It looks like you've got two threads going with the same problem. Please restrict it to one.

Please see our site guidelines here:
https://forum.posit.co/guidelines#keep-tidy

1 Like