简体   繁体   中英

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)

One stringi option could be:

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

[1] 1 2 1 2 5 4 6 1
result_vector <- nchar(v) - sapply(stringr::str_locate_all(as.character(v), "1"), max) + 1

由于数字是 1 或 0,因此您的问题在逻辑上等同于计算尾随零的数字。

result_vector <- nchar(x) - nchar(trimws(x, "right", "0")) + 1L

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM