How to make a function which has continuous argument (without any gap or commas)


#1

Hi,
I want to make a program which could read my argument and then sum them up. I have already saved different characters which would be summed up by this function for example ( H=1, C=12, N=14, O=16)

I want my function to read my input as (HCNO). Please suggest me, how can i make this happen. Although i am able to creat a function but not with the input same as i have mentioned above. Function which i have made is as follows

carbon_number<-function(char1, char2,…){
formula<-sum(char1, char2,…)
return(formula)
}

In here input is- H,C,N,O
And i want my input as - HNCO

Thanks


#2

#3

Please tell me any other way without any special packages!

Thank you!


#4

There are multiple solutions in the thread I’ve linked. Only the last one depends on quosures and tidyverse. If you have a very specific reason not to use additional packages, then you should explain it in more detail to make it clear what are the dependencies.


#6

I don’t think you’ll be able to do this as a function with a single argument. You will at least need to pass in a vector of references. You can then strsplit your character string on empty characters to get a vector of individual characters.

If we use the reference

ref <- c(A = 1, 
         B = 2,
         C = 3,
         D = 4,
         E = 5,
         F = 6)

and define the function

carbon_number <- function(compound, ref){
  compound <- unlist(strsplit(compound, ""))
  sum(ref[compound])
}

We can then generate sums as follows:

carbon_number("ABC", ref = ref) # 6
carbon_number("AFD", ref = ref) # 11

#7

As a side note, I’m curious what you mean by “carbon number.” The weights you give ( H=1, C=12, N=14, O=16) look very similar to atomic masses for various elements.


#8

I’m closing this thread as it’s an almost word-for-word duplicate of this same question yesterday:


#9