What is the best way to get the second and last value in R data.frame?

Suppose I have a data.frame called SLV and I use the tail () function. I will get this:

> tail(SLV) SLV.Open SLV.High SLV.Low SLV.Close SLV.Volume SLV.Adjusted 2010-12-06 28.99 29.64 28.88 29.51 57561800 29.51 2010-12-07 29.95 30.00 28.03 28.08 69143800 28.08 2010-12-08 28.33 28.46 27.34 27.70 58203800 27.70 2010-12-09 28.10 28.36 27.83 28.03 36759200 28.03 2010-12-10 27.80 28.11 27.38 27.98 30602700 27.98 2010-12-13 28.84 29.04 28.59 28.87 25901800 28.87 

tail () uses the last 6 values ​​by default, but it is easy to get only the last value.

 >tail(SLV, n=1) SLV.Open SLV.High SLV.Low SLV.Close SLV.Volume SLV.Adjusted 2010-12-13 28.84 29.04 28.59 28.87 25901800 28.87 

But what is the best way to get the second back on the last day? In our SLV example, this will be a string dated 2010-12-10.

+4
source share
4 answers
 head(tail(SLV, n=2), n=1) 

or

 SLV[nrow(SLV)-1,] 

will do it.

+14
source

For another alternative:

 tail(SLV,2)[-2] 
+4
source

head (tail (SLV, n = 2), n = 1)

+3
source

Very slightly more general than SLV [nrow (SLV) -1,]:

 SLV[rev(1:nrow(SLV))[2],] 

The literal [2] can be replaced with a vector, which is perhaps more accurate if more than one line is required.

0
source

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


All Articles