AnilGoyal
AnilGoyal

Reputation: 26218

How to extract last occurrence of a particular 'string' from a vector

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)

Upvotes: 2

Views: 603

Answers (3)

tmfmnk
tmfmnk

Reputation: 39858

One stringi option could be:

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

[1] 1 2 1 2 5 4 6 1

Upvotes: 3

ekoam
ekoam

Reputation: 8844

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

Upvotes: 1

Vasily A
Vasily A

Reputation: 8626

result_vector <- nchar(v) - sapply(stringr::str_locate_all(as.character(v), "1"), max) + 1

Upvotes: 1

Related Questions