Access the Last Value in a Vector Using R Programming
R Programming: Vector Exercise-12 with Solution
Write a R program to access the last value in a given vector.
Sample Solution :
R Programming Code :
# Create a numeric vector 'x' with elements 10, 20, 30, 20, 20, 25, 9, and 26
x = c(10, 20, 30, 20, 20, 25, 9, 26)
# Print a message indicating the display of the original vector
print("Original Vectors:")
# Print the contents of vector 'x'
print(x)
# Print a message indicating the access of the last value in the vector
print("Access the last value of the said vector:")
# Access and print the last value of vector 'x' using the tail function
print(tail(x, n=1))
Output:
[1] "Original Vectors:" [1] 10 20 30 20 20 25 9 26 [1] "Access the last value of the said vector:" [1] 26
Explanation:
- x = c(10, 20, 30, 20, 20, 25, 9, 26): Creates a numeric vector x with the elements 10, 20, 30, 20, 20, 25, 9, and 26.
- print("Original Vectors:"): Prints the label "Original Vectors:" to indicate that the following output will display the vector x.
- print(x): Prints the contents of vector x.
- print("Access the last value of the said vector:"): Prints the label "Access the last value of the said vector:" to indicate that the following output will show the last value of vector x.
- print(tail(x, n=1)): Uses the tail function to access and print the last value of vector x. The argument n=1 specifies that only the last element should be returned.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to count the specific value in a given vector.
Next: Write a R program to find second highest value in a given vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics