# Calculate the sum of all the characters

#1

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

#2

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

Whta is %>% this for?

#4

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,

#5

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)

#6

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,

#7

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://community.rstudio.com/guidelines#keep-tidy

closed

This topic has been closed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.
#8