komodovaran_ komodovaran_ - 1 year ago 64
R Question

Find local minima/maxima and and use only this range for plotting

Below I have some data. Please paste into a text file as CSV, as I couldn't figure out how to export it as vectors :)

Anyway, when scatterplotted you'll notice there's a maximum. How can I make a fit (in this case just a linear, although not entirely accurate) only from the range

x = 0
to
x = max(y)
, and then another fit (perhaps exponential decay) from the maximum to the end point? See sketch below.

enter image description here

time;intensity
0;2.17645
30;1.93959
60;2.66259
90;2.90125
120;2.5585
150;2.68808
180;3.06872
210;2.78406
240;3.03446
270;3.00371
300;2.92382
330;2.9213
360;2.86571
390;2.67248
420;2.48212
450;2.58491
480;2.53085
510;2.46214
540;2.38609
570;2.03002
600;1.8867
630;1.75795
660;1.69764
690;1.71163
720;1.59365
750;1.67867
780;1.59154
810;1.47798
840;1.43321
870;1.4091
900;1.32017
930;1.31044
960;1.28891
990;1.31004
1020;1.24349
1050;1.17192
1080;1.08548
1110;1.13026
1140;1.14576
1170;1.12595
1200;1.16716
1230;1.15284
1260;1.12913
1290;1.14195
1320;1.11694
1350;1.16297
1380;1.04345
1410;1.0932
1440;1.10847
1470;1.09431
1500;1.02416
1530;1.00733
1560;1.15768
1590;1.09288
1620;1.11773
1650;1.15572
1680;1.02918
1710;1.12721
1740;1.14438

Answer Source

The easiest way to do this would be to split your data into two at the point where the maximum occurs and fit them independantly?

This can be achieved by the following code;

 data <- read.csv('./in.csv')
 max <- which.max(data$intensity)

 start <- data[1:max,]     
 end <- data[max:dim(data)[1],]

which just returns the index where the maximum is reached, and splits on that, dim returns the shape of the dataframe, and we are selecting the number of rows.

If you are looking to smooth the top of the data and not use the explict maximum value, there is a nice example using rollaply here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download