0
0
R Programmingprogramming~5 mins

Numeric and character vectors in R Programming

Choose your learning style9 modes available
Introduction

Vectors are like lists that hold many items of the same type. Numeric vectors hold numbers, and character vectors hold words or letters.

When you want to store a list of numbers, like ages or scores.
When you need to keep a list of names or words together.
When you want to do math or text operations on a group of values.
When you want to organize data in a simple, easy-to-use way.
Syntax
R Programming
numeric_vector <- c(1, 2, 3, 4)
character_vector <- c("apple", "banana", "cherry")

The c() function combines values into a vector.

All items in a vector must be the same type: all numbers or all characters.

Examples
Create a numeric vector numbers and a character vector words.
R Programming
numbers <- c(10, 20, 30, 40)
words <- c("cat", "dog", "bird")
If you mix numbers and characters, R converts all to characters.
R Programming
mixed <- c(1, "two", 3)
Create empty numeric and character vectors with fixed lengths.
R Programming
empty_numeric <- numeric(5)
empty_character <- character(3)
Sample Program

This program creates a numeric vector and a character vector, then prints both.

R Programming
numeric_vector <- c(5, 10, 15)
character_vector <- c("red", "green", "blue")

print(numeric_vector)
print(character_vector)
OutputSuccess
Important Notes

Vectors are the basic building blocks for data in R.

Use typeof() to check the type of a vector.

Mixing types in a vector causes automatic conversion to a common type.

Summary

Numeric vectors hold numbers, character vectors hold text.

Use c() to create vectors.

All elements in a vector must be the same type.