Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R regex to find and replace code in rstudio

Tags:

regex

r

rstudio

I would like to make several changes to a code script. I need to change the way how certain dataframes were subsetted. Specifically I need a way of using regex for editing my code with R studio.

I need to transform several dataframes that follow this format,

 variablex_indicatory$n[i]

To this,

 variablex_indicatory$n[variablex_indicatory$n==i]

Since I have many combinations of variables and indicators (e.g. variable1_indicator2, variable3_indicator1, etc.). what I need is to be able to replace what is after $n[ from i] to variablex_indicatory$n ==

So I need to specify in regex, find $n[ and replace with $n[whatever is before $n goes here ==

I would left the i untouched as it does not need to be change.

How to do this surpases my current knowledge of regular expressions (obviously) I hope someones can help, thanks in advance again and please let me know if I was not clear enough.

like image 505
csmontt Avatar asked Jun 17 '15 16:06

csmontt


Video Answer


1 Answers

Assuming each line looks roughly like this: variablex_indicatory$n[i], then you can put this regex in the find box: (^.+)(\$n\[)(i\]) and this regex in the replace box: \1\2\1==\3 and click "replace all."

If you have more complex code, then you need to do a better job of defining the first group (My example selects from the beginning of the line up to the dollar sign ($)). Here's one variation for the first group: (variab.+). What you actually use will depend on the unspecified specifics of your situation.

like image 57
D. Woods Avatar answered Oct 02 '22 19:10

D. Woods