Hi there,
Not totally clear on your expected result, but does the new function get you there?
ref <- c(A = 1, B = 2, C = 3)
carbon_number_orig <- function(compound, ref){
compound <- unlist(strsplit(compound, ""))
sum(ref[compound])
}
carbon_number_orig("AAAAA", ref = ref)
#> [1] 5
carbon_number_new <- function(compound, ref){
compound <- unlist(strsplit(compound, ""))
sum(ref[head(compound, -1)])
}
carbon_number_new("AAAAA", ref = ref)
#> [1] 4
Created on 2018-03-01 by the reprex package (v0.2.0).
In the new function, head(compound, -1) drops the last element of the compound vector, so instead of "A", "A", "A", "A", "A", you get "A", "A", "A", "A".