Search code examples
rregexsubset

Efficient way to edit index ranges in subsetting calls


The everpresent problem of porting code from a language whose indices start with zero to a language whose indices start with one, again... In this case I want to port a long block that goes like

x[0:3] =  c(65,43, 22)
x[4:7] = c(23, 17,93, 7)

and so on for dozens of lines. I'm reasonably comfortable with regex, so I can generate a pattern
that searches for , e.g. "\[[0:9]{1,}:" and so on, but I'd hate to have to then extract each numeric sequence, convert to numeric, add one, and then paste0 it all back together.
Is there a better approach, and for that matter, is there an existing R package that can automagically "shift" all the indices in text strings?

Followup: yeah I could dump this file into the source language, create x , print x values, and feed that to R, but I'd rather not.


Solution

  • Much later, it occurs to me that, instead of trying to replace numerals, modifying the index definitions is much easier.

    Example:

    frist <- '[0:3]'
    secnod <- gsub('[[]','[1+(', frist) 
    finlaly <- gsub('[]]',')]',secnod)