Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
R is a programming language that is used for statistical analysis and graphical representation. R is not just a programming language but also an environment that allows you to write code and create high-quality graphs with mathematical symbols. Download the R language and R studio in your windows, Linux or macOS and start learning!
In this article, we will discuss how to create, modify and access a R Vector.
A Vector in R programming is a sequence containing the same type of data. A vector is a basic data structure that is homogeneous in nature i.e., a vector can hold only a single type of data in it. We can store any kind of data type like - logical, integer, double, character, complex or raw in a vector. A vector is a one-dimensional data structure.
How to create a vector in R?
There are many different methods for creating a vector in R programming - using a c() function, using a : (colon) and using a seq() function. Let’s understand how to use each one of these in detail.
Using a c() function
c() is a concatenate function that is generally used to create a vector in R programming.
Note: A vector is strictly one-dimensional.
Syntax
variable_name <- c(list_of_values)
variable_name is the name of the variable in which the vector will be stored.
c() is the concatenation function.
list_of_values is a list of comma-separated values that can be any data type like logical, integer, double, character, complex or raw.
Example: Suppose we want to create a vector with data 1, 2, 3 and 4.
Code
x <- c(1, 2, 3, 4)
Output
[1] 1 2 3 4 5
Create a vector whose indexes are named
You can also create a vector in which each element has a name.
Example: Suppose we want to create a vector in which the values 10, 20 and 30 are named as first, second and third respectively.
Code
y <- c("first" =1, "second" =2, "third"=3)
y
Output
first second third
1 2 3
Coercion of vectors in R
A Vector in R programming is a homogeneous data structure. If you try to store data of different types then it will coerce elementsto the same type. Let’s understand with an example -
Suppose we have the following data - 1, 2.0, ninja and we try to store this in a vector. What do you think will happen?
The code for storing the values will be as follows -
y <- c(1, 2.0, "ninja")
If you view the vector y it will be as follows:
Output
[1] "1" "2" "ninja"
Let’s check the type of the variable y.
typeof(y)
Output
[1] "character"
So, as you can see from the above example, R changed all the data into character data type. This is coercion in R programming.
Remember this about coercion:
The rough order of the data types is - logical < integer < numeric < complex < character < list.
The values are converted to the simplest data structure.
TRUE will be converted to 1 and FALSE will be converted to 0.
Using a : (colon)
If you want to store consecutive numbers in a vector then you can use the : (colon).
Syntax
variable_name = start_number : end_number
variable_name is the name of the variable in which the vector is stored.
start_number is the first number with which the sequence will start.
end_number is the last number with which the sequence will end.
Note: both the start_number and the end_number are inclusive i.e. if we have 1:4 then the vector will store values 1,2,3,4.
Example: Let’s create a vector with number from 1 to 10 using the : (colon).
Code
x <- 1:10
x
Output
[1] 1 2 3 4 5 6 7 8 9 10
You can also store negative numbers.
Code
y <- 10:-3
y
Output
[1] 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3
Using seq() function
The seq() function can be used to create a sequence of values in a vector in R programming. This function takes two optional arguments - “length”, which is used to define the number of elements that should be there in the vector and “by” which defines the step size. Step size is the difference between each element in the vector.
R vectors are fundamental data structures used to store collections of elements of the same type. R vectors are fundamental data structures used to store collections of elements of the same type. There are two main categories of vectors in R:
Atomic Vectors (Basic Building Blocks)
These are the most common type of vectors and come in six basic data types, each with its own subheading for clarity:
Logical vectors: Logical vectors contain TRUE, FALSE, or NA (missing value) values. They are used to represent logical conditions and often serve as the result of comparisons or conditional statements.
Integer vectors: Integer vectors store whole numbers (integers) without any decimal places. They are ideal for representing counts, identifiers, or data where decimals are not meaningful.
Double vectors: Double vectors store real numbers, which include both integers and decimals. It's important to note that integer vectors are technically a subtype of double vectors, as they can also be represented using decimals (e.g., 5 can also be written as 5.0). Double vectors are more versatile and are the default choice for numerical data unless you specifically need whole numbers.
Character vectors: Character vectors contain sequences of text characters, including letters, numbers, and symbols. They are used to store text data like names, labels, or any textual information.
Complex vectors: Complex vectors store complex numbers, which are numbers with a real and imaginary part. These are less commonly used in typical data analysis but can be useful for specific mathematical applications.
Raw vectors: Raw vectors store raw bytes of data in their most basic form. This allows for low-level data manipulation but is not frequently used for standard data analysis tasks. They are more common in specialized programming scenarios.
Lists
Lists are a flexible data structure in R that can hold elements of different data types within a single vector. Unlike atomic vectors where all elements must be the same type, lists provide more versatility for storing diverse data.
Length of R Vector
The length of an R vector refers to the total number of elements it contains. It's an essential property that determines how many values the vector holds. There are two primary ways to find the length of a vector in R:
1. Using the length() function: This is the most common method. Simply apply the length() function to your vector variable name.
my_vector <- c(10, 20, 30, "apple")
vector_length <- length(my_vector)
cat("The length of the vector is:", vector_length)
2. Accessing the length property: You can directly access the length property of the vector object.
vector_length <- my_vector$length
cat("The length of the vector is:", vector_length)
Understanding the type and length of your R vectors is crucial for effective data manipulation and analysis.
Access elements of a vector
There are three ways of accessing the data stored in the vector in R programming. The data stored in a vector can be accessed by using the index. You can use integer, logical and character indexes.
1) Indexing with integer vector
In vector, the indexing starts from 1. Let’s take an example vector containing values - 10, 20, 30, 40, 50.
1
2
3
4
5
10
20
30
40
50
Access the data using a positive integer value.
Example: Suppose we have a vector with values - 10, 20, 30, 40, 50 and we want to access the value 30.
Code
x[3]
Output
[1] 30
If you use a negative number as the index then all the values except that value will be returned.
Example : Suppose we have a vector with values - 10, 20, 30, 40, 50.
Code
x[-3]
Output
[1] 10 20 40 50
The index is -3 so all the values except x[3]=30 will be returned.
Access multiple index values.
Example: Suppose we have a vector with values - 10, 20, 30, 40, 50 and we want to access the values 20, 40.
Code
x[c(2,4)]
Output
[1] 20 40
2) Indexing with a logical vector
The index with the value TRUE will be returned and the index with value FALSE will be ignored.
Example : Suppose we have a vector with values - 10, 20, 30, 40, 50 and we want to access the values 20, 40.
Code
x[c(FALSE, TRUE, FALSE, TRUE, FALSE)]
Output
[1] 20 40
3) Indexing with a character vector
In the case of named vectors, use the name as the index to return vector values.
Use the assignment operator (<-) to modify the data of a vector in R programming.
Example
Suppose we have a vector ‘x’ with values - 10, 20, 30 and 40.
Run the following code to change the value 20 to 200.
Code
x[2] <- 200
x
Output
[1] 10 200 30 40 50
Vector Operation
Vector operations in R refer to the various operations that can be performed on vectors, which are one-dimensional data arrays. Here are the common vector operations in R:
1. Addition: Perform element-wise addition of two vectors of the same length.
Vectors can be used in many different contexts, including:
1. In R, vectors are frequently used to store and manage data. They are able to store logical values, character values, and numeric values.
2. Mathematical processes involving many values or the application of operations to whole datasets are made efficient and convenient by vectors.
3. When aggregating, filtering, and transforming datasets, statistical and data analysis tasks heavily rely on vectors.
5. Data visualization and analysis are made possible by the frequent use of vectors to represent data points in graphs and plots.
6. To store and manipulate feature sets, labels, and predictions, machine learning algorithms frequently use vectors. Check this out: R Programming language
Frequently Asked Questions
What is a vector in R with example?
A vector in R is a basic data structure storing elements of the same type. For example, c(1, 3, 5, 7) creates a numeric vector.
What are the 4 types of vectors in R?
The 4 types of vectors in R are logical, integer, double, and character. There are additional two types as well: complex, and raw.
What is vector operation in R?
Operations like addition, subtraction, multiplication, and element-wise comparisons can be performed on vectors of compatible types.
Where is vector used?
Vectors are fundamental for data storage and manipulation in R. They are used in various tasks like calculations, data analysis, and creating statistical models.
Conclusion
In this article, we have discussed R Vectors (With Examples). R vectors are like building blocks for data in R. They come in different flavors, like numbers, text, or even a mix of both! You can easily create and work with them to store information and perform calculations.