Create Numeric, Character, and Logical Vectors in R
Write a R program to create three vectors numeric data, character data and logical data. Display the content of the vectors and their type.
Sample Solution :
R Programming Code :
# Create a numeric vector 'a' with specified values
a = c(1, 2, 5, 3, 4, 0, -1, -3)
# Create a character vector 'b' with specified color names
b = c("Red", "Green", "White")
# Create a logical vector 'c' with specified boolean values
c = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)
# Print the contents of the numeric vector 'a'
print(a)
# Print the data type of the vector 'a'
print(typeof(a))
# Print the contents of the character vector 'b'
print(b)
# Print the data type of the vector 'b'
print(typeof(b))
# Print the contents of the logical vector 'c'
print(c)
# Print the data type of the vector 'c'
print(typeof(c))
Output:
[1] 1 2 5 3 4 0 -1 -3 [1] "double" [1] "Red" "Green" "White" [1] "character" [1] TRUE TRUE TRUE FALSE TRUE FALSE [1] "logical"
Explanation:
- Create Numeric Vector a:
- a = c(1, 2, 5, 3, 4, 0, -1, -3)
- Defines a numeric vector a with the values: 1, 2, 5, 3, 4, 0, -1, -3.
- Create Character Vector b:
- b = c("Red", "Green", "White")
- Defines a character vector b with the values: "Red", "Green", "White".
- Create Logical Vector c:
- c = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)
- Defines a logical vector c with the values: TRUE, TRUE, TRUE, FALSE, TRUE, FALSE.
- Print Vector a:
- print(a)
- Displays the contents of vector a.
- Print Data Type of a:
- print(typeof(a))
- Shows the data type of vector a, which is "double" (numeric).
- Print Vector b:
- print(b)
- Displays the contents of vector b.
- Print Data Type of b:
- print(typeof(b))
- Shows the data type of vector b, which is "character".
- Print Vector c:
- print(c)
- Displays the contents of vector c.
- Print Data Type of c:
- print(typeof(c))
- Shows the data type of vector c, which is "logical".
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to read the .csv file and display the content.
Next: Write a R program to create a 5 × 4 matrix , 3 × 3 matrix with labels and fill the matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics