Create Vectors of Numeric, Complex, Logical, and Character Types in R
R Programming: Vector Exercise-1 with Solution
Write a R program to create a vector of a specified type and length. Create vector of numeric, complex, logical and character types of length 6.
Sample Solution :
R Programming Code :
# Create a numeric vector of length 5 initialized with zeros
x = vector("numeric", 5)
# Print the label for the numeric vector
print("Numeric Type:")
# Print the numeric vector
print(x)
# Create a complex vector of length 5 initialized with zeros
c = vector("complex", 5)
# Print the label for the complex vector
print("Complex Type:")
# Print the complex vector
print(c)
# Create a logical vector of length 5 initialized with FALSE
l = vector("logical", 5)
# Print the label for the logical vector
print("Logical Type:")
# Print the logical vector
print(l)
# Create a character vector of length 5 initialized with empty strings
chr = vector("character", 5)
# Print the label for the character vector
print("Character Type:")
# Print the character vector
print(chr)
Output:
[1] "Numeric Type:" [1] 0 0 0 0 0 [1] "Complex Type:" [1] 0+0i 0+0i 0+0i 0+0i 0+0i [1] "Logical Type:" [1] FALSE FALSE FALSE FALSE FALSE [1] "Character Type:" [1] "" "" "" "" ""
Explanation:
- x = vector("numeric", 5):
- Creates a numeric vector x of length 5, initialized with zeros.
- print("Numeric Type:"):
- Prints the label "Numeric Type:" to indicate the following output is for the numeric vector.
- print(x):
- Prints the numeric vector x.
- c = vector("complex", 5):
- Creates a complex vector c of length 5, initialized with zeros (complex type).
- print("Complex Type:"):
- Prints the label "Complex Type:" to indicate the following output is for the complex vector.
- print(c):
- Prints the complex vector c.
- l = vector("logical", 5):
- Creates a logical vector l of length 5, initialized with FALSE.
- print("Logical Type:"):
- Prints the label "Logical Type:" to indicate the following output is for the logical vector.
- print(l):
- Prints the logical vector l.
- chr = vector("character", 5):
- Creates a character vector chr of length 5, initialized with empty strings.
- print("Character Type:"):
- Prints the label "Character Type:" to indicate the following output is for the character vector.
- print(chr):
- Prints the character vector chr
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: R Programming Exercises Home.
Next: Write a R program to add two vectors of integers type and length 3.
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-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics