I am trying to develop a really simple function in r, the idea is that;
Say I have the following sequence "UUDDDDUDU" where "U" = 1 and "D" = -1. I want to count the following: +1, +1, -1, -1, -1, -1, +1, -1, +1. Where I get the final number as -1.
funky <- function(n, s){
current_level = 0
U = 1
D = -1
for(i in 1:n){
if(s[i] == "U"){current_level +1}
if(s[i] == "D"){current_level -1}
}
}
funky(9, UUDDDDUDU)
Any pointers in the right direction would be great!
You could use stringr::str_count
s <- "UUDDDDUDU"
library(stringr)
str_count(s, 'U') - str_count(s, 'D')
# [1] -1
or more generally
library(purrr)
weights <- c(U = 1L, D = -1L)
sum(imap_int(weights, ~str_count(s, .y)*.x))
# [1] -1
Base R solution (using weights and s as defined above)
sum(weights[strsplit(s, '')[[1]]])
# [1] -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With