[英]R regex to find and replace code in 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.
具体来说,我需要一种使用正则表达式来编辑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 (eg variable1_indicator2
, variable3_indicator1
, etc.). 由于我有许多变量和指标的组合(例如
variable1_indicator2
, variable3_indicator1
等)。 what I need is to be able to replace what is after $n[
from i]
to variablex_indicatory$n ==
我需要的是能够替换
$n[
从i]
到variablex_indicatory$n ==
So I need to specify in regex, find $n[
and replace with $n[whatever is before $n goes here ==
所以我需要在正则表达式中指定,找到
$n[
并替换为$n[whatever is before $n goes here ==
I would left the i
untouched as it does not need to be change. 我会离开
i
不变,因为它并不需要被改变。
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. 如何做到这一点超过了我目前对正则表达式的了解(显然)我希望有人可以提供帮助,再次提前感谢,如果我不够清楚,请告诉我。
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." 假设每一行看起来大致如下:
variablex_indicatory$n[i]
,那么你可以将这个正则表达式放在查找框中: (^.+)(\\$n\\[)(i\\])
和替换框中的这个正则表达式: \\1\\2\\1==\\3
并单击“全部替换”。
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.+)
. 这是第一组的一个变体:(
(variab.+)
。 What you actually use will depend on the unspecified specifics of your situation. 您实际使用的将取决于您的具体情况。
Try this: 试试这个:
string<-"variablex_indicatory$n[i]"
first<-sub('\\[.*]','',string)
second<-sub('.*\\[(.*)\\]','\\1',string)
paste(first,'[',first,'==',second,']',sep='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.