[R] interval between specific characters in a string...
Martin Morgan
mtmorg@n@b|oc @end|ng |rom gm@||@com
Sat Dec 3 01:39:20 CET 2022
You could split the string into letters and figure out which ones are �b�
which(strsplit(x, "")[[1]] == "b")
and then find the difference between each position, �anchoring� at position 0
> diff(c(0, which(strsplit(x, "")[[1]] == "b")))
[1] 2 4 1 6 4
From: R-help <r-help-bounces using r-project.org> on behalf of Evan Cooch <evan.cooch using gmail.com>
Date: Friday, December 2, 2022 at 6:56 PM
To: r-help using r-project.org <r-help using r-project.org>
Subject: [R] interval between specific characters in a string...
Was wondering if there is an 'efficient/elegant' way to do the following
(without tidyverse). Take a string
abaaabbaaaaabaaab
Its easy enough to count the number of times the character 'b' shows up
in the string, but...what I'm looking for is outputing the 'intervals'
between occurrences of 'b' (starting the counter at the beginning of the
string). So, for the preceding example, 'b' shows up in positions
2, 6, 7, 13, 17
So, the interval data would be: 2, 4, 1, 6, 4
My main approach has been to simply output positions (say, something
like unlist(gregexpr('b', target_string))), and 'do the math' between
successive positions. Can anyone suggest a more elegant approach?
Thanks in advance...
______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
More information about the R-help
mailing list