Adam Amin
Adam Amin

Reputation: 1456

How to select every other xth row while keeping the first and last row

Assume we have the following data:

Measure         Value
2.00              8
2.9993544         1
2.9993925         8
2.9994541        15
2.9994957         4
2.9995287         1
2.9995569        12
2.9996014         1
2.9996418        13
2.9996768         1
2.9997152         3
3                21

I want to select every second row but keeping the first row and last row. The expected output would be:

Measure         Value
2.00              8
2.9993925         8
2.9994957         4
2.9995569        12
2.9996418        13
2.9997152         3
3                21

I tried the following with several data sets but it removes the last row:

df[seq(1, nrow(df), 2), ]

How can I fix that?

Upvotes: 0

Views: 25

Answers (1)

d.b
d.b

Reputation: 32548

Use vector recycling.

d[c(TRUE, FALSE) | (seq(NROW(d)) == NROW(d)),]
#    Measure Value
#1  2.000000     8
#3  2.999392     8
#5  2.999496     4
#7  2.999557    12
#9  2.999642    13
#11 2.999715     3
#12 3.000000    21

Upvotes: 1

Related Questions