[R] Processing a hierarchical string name

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Jun 28 22:56:33 CEST 2023

On Wed, 28 Jun 2023 20:29:23 +0000
Kevin Zembower via R-help <r-help using r-project.org> wrote:

> I think my algorithm for the labels is:
> 1. keep everything from the last "!!" up to and including the last
> character
> 2. for everything remaining, replace each "!!.*:" group with a single
> space.

If you remove the initial ' !!', the problem becomes a more tractable
"replace each group of non-'!' followed by '!!' with one space":

bg3_race_sum$label |>
 (\(.) sub('^ !!', '', .))() |>
 (\(.) gsub('[^!]*!!', ' ', .))()

But that solution could have been impossible if the task was slightly

> I can split the label using str_split(label, pattern = "!!") to get a
> vector of strings, but don't know how to work on the last string and
> all the rest of the strings separately.

str_split() would have given you a list of character vectors. You can
use lapply to evaluate a function on each vector inside that list.
Inside the function, use length(x) (if `x` is the argument of the
function) to find out how many spaces to produce and which element of
the vector is the last one. (For code golf points, use rev(x)[1] to get
the last element.)

Best regards,

More information about the R-help mailing list