Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

If for argument's sake, I want the last five elements of a 10-length vector in Python, I can use the "-" operator in the range index so:

>>> x = range(10)

>>> x

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> x[-5:]

[5, 6, 7, 8, 9]

>>>

What is the best way to do this in R? Is there a cleaner way than my current technique which is to use the length() function?

> x <- 0:9

> x

 [1] 0 1 2 3 4 5 6 7 8 9

> x[(length(x) - 4):length(x)]

[1] 5 6 7 8 9

The question is related to time series analysis btw where it is often useful to work only on recent data

1 Answer

0 votes
by
edited by

To print the last n elements of a vector, you can use the tail and head functions as follows:

x <- 1:10

tail(x,5)

[1]  6  7  8  9 10

To print everything but the last five elements:

 head(x,n=-5)

[1] 1 2 3 4 5

You can also use the following functions:

x[length(x) - (4:0)]                           

[1]  6  7  8  9 10

x[seq.int(to = length(x), length.out = 5)] 

[1]  6  7  8  9 10

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
2 answers
+1 vote
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...