Take data from rows in R using regex

Now the line looks like this:

"Interest.USD,Vol=[Integrated,(0,0.101),(0.2,0.108),(1,0.110),(2,0.106),
(3,0.102),(4,0.09),(5,0.091),(6,0.09128272)],Drift=[Integrated,(0.002,0.09),
(0.24,0.0007),(0.4,0.007),(1,-0.033),(2,-0.005),(3,-0.0041),
(4,-0.3505),(5,-0.65),(7,-0.08346),(8,-0.049),(9,-0.0613),(10,-0.019)],
Risk_Neutral=YES,Lambda=0.09,FX_Volatility=0.01,FX_Correlation=0.9"

I want to capture data following β€œVol” and β€œDrift” in matrix format, for example:

Matrix Vol:

0,0.101
0.2,0.108
1,0.110
2,0.106
3,0.102
4,0.09
5,0.091
6,0.09128272

as well as one value equal to 0.09 for Lambda. I think I shuold to use regex, but I do not know what about this. Any suggestion?:)

PS I tried to use:

str_extract_all(text,'[ .+? ]')

try to get bewteen [and] data, but it returns ".".

+4
source share
2 answers

R. , , , a. , : getcapturedmatches().

expr <- "(Vol|Drift)=\\[Integrated,([^\\]]*)\\]"
mm <- regcapturedmatches(a,gregexpr(expr,a, perl=T))[[1]]
expr <- "\\(([^,]+),([^,]+)\\)"
vv <- regcapturedmatches(mm[,2],gregexpr(expr,mm[,2], perl=T))

Vol Drift mm, - vv. data.frame

tt <- Map(data.frame, col=mm[,1], val=lapply(vv, 
    function(x) {class(x)<-"numeric"; x}))
dd<-do.call(rbind, unname(tt))

dd

     col  val.1       val.2
1    Vol  0.000  0.10100000
2    Vol  0.200  0.10800000
3    Vol  1.000  0.11000000
4    Vol  2.000  0.10600000
5    Vol  3.000  0.10200000
6    Vol  4.000  0.09000000
7    Vol  5.000  0.09100000
8    Vol  6.000  0.09128272
9  Drift  0.002  0.09000000
10 Drift  0.240  0.00070000
11 Drift  0.400  0.00700000
12 Drift  1.000 -0.03300000
13 Drift  2.000 -0.00500000
14 Drift  3.000 -0.00410000
15 Drift  4.000 -0.35050000
16 Drift  5.000 -0.65000000
17 Drift  7.000 -0.08346000
18 Drift  8.000 -0.04900000
19 Drift  9.000 -0.06130000
20 Drift 10.000 -0.01900000

.

,

Map(function(a,b) {class(b)<-"numeric"; b}, mm[,1], 
    lapply(vv, function(x) {class(x)<-"numeric"; x}))

.

+5

. , .

Vol=.*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*\(([\d,.]+)\).*(?=,Drift)

DEMO

. .

+2

Source: https://habr.com/ru/post/1545253/


All Articles