R Programming: Create a Vector and find its Length and Dimension
R Programming: Vector Exercise-24 with Solution
Write a R program to create a vector and find the length and the dimension of the vector.
Sample Solution :
R Programming Code :
# Create a vector 'v' with the elements 1, 3, 5, 7, and 9
v = c(1, 3, 5, 7, 9)
# Print a message indicating the original vector
print("Original vectors:")
# Print the content of the vector 'v'
print(v)
# Print a message indicating the dimension of the vector
print("Dimension of the vector:")
# Print the dimension of the vector 'v' (returns NULL for a 1D vector)
print(dim(v))
# Print a message indicating the length of the vector
print("length of the vector:")
# Print the length of the vector 'v'
print(length(v))
Output:
[1] "Original vectors:" [1] 1 3 5 7 9 [1] "Dimension of the vector:" NULL [1] "length of the vector:" [1] 5
Explanation:
- Create a vector:
- v = c(1, 3, 5, 7, 9)
A vector v is created containing the numeric elements 1, 3, 5, 7, and 9. - Print message (Original vector):
- print("Original vectors:")
Prints a message indicating that the following output will show the original vector. - Display the vector:
- print(v)
Displays the content of the vector v. - Print message (Dimension of the vector):
- print("Dimension of the vector:")
Prints a message indicating that the following output will show the dimension of the vector. - Display the dimension of the vector:
- print(dim(v))
Displays the dimension of the vector v. For a simple vector, this will return NULL because vectors are one-dimensional. - Print message (Length of the vector):
- print("length of the vector:")
Prints a message indicating that the following output will show the length of the vector. - Display the length of the vector:
- print(length(v))
Displays the number of elements in the vector v, which in this case is 5.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to convert two columns of a data frame to a named vector.
Next: Write a R program to combines two given vectors by columns, rows.
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://www.w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics