Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple function to count plus 1 and negative 1

Tags:

r

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!

like image 705
user113156 Avatar asked Mar 19 '26 14:03

user113156


1 Answers

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
like image 98
IceCreamToucan Avatar answered Mar 22 '26 04:03

IceCreamToucan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!