2

I have a vector of several binary numbers stored in it. Since these are already filtered, it is also known that all are greater than 0.

v <- c(1, 10, 11, 110, 10000, 101000, 100100000, 100001)

Now I want a result_vector (vector because input vector is a column in a data frame) giving me position/location of last occurrence of 1 in the vector v. I am trying stringr::str_locate(as.Charachter(v), "1")[,2] but it gives me ending position of first occurence of this vector. stringr::str_locate_all gives result in a list instead therefore not useful in the context. Moreover, I want this position counted from backwards. However, if I can extract location from left that can be converted to reverse by substracting from nchar(as.Charachter(v)). Please guide me how can I proceed to get a result like

result_vector = c(1, 2, 1, 2, 5, 4, 6, 1)
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
  • 1
    do you need to find position of `1` in each element of the vector? your input vector has 8 elements but your result has 7 – Vasily A Nov 02 '20 at 07:23
  • Yes @VasilyA thanks for pointing out the error. I have corrected the desired_output, please. – AnilGoyal Nov 02 '20 at 07:27

3 Answers3

3

One stringi option could be:

stri_locate_first(stri_reverse(v), fixed = "1")[, 1]

[1] 1 2 1 2 5 4 6 1
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
1
result_vector <- nchar(v) - sapply(stringr::str_locate_all(as.character(v), "1"), max) + 1
Vasily A
  • 8,256
  • 10
  • 42
  • 76
1

As the digits are either 1 or 0, your question is logically equivalent to counting the number trailing zeros.

result_vector <- nchar(x) - nchar(trimws(x, "right", "0")) + 1L
ekoam
  • 8,744
  • 1
  • 9
  • 22