Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Vector in R Programming Language?
3.
How to create a vector in R?
3.1.
Using a c() function
3.1.1.
Syntax
3.1.2.
Example: Suppose we want to create a vector with data 1, 2, 3 and 4. 
3.1.3.
Create a vector whose indexes are named
3.1.4.
Coercion of vectors in R
3.2.
Using a : (colon) 
3.2.1.
Syntax 
3.2.2.
Example: Let’s create a vector with number from 1 to 10 using the : (colon). 
3.3.
Using seq() function
3.3.1.
Syntax
3.3.2.
Example 
4.
Types of R Vectors
4.1.
Atomic Vectors (Basic Building Blocks)
4.2.
Lists
5.
Length of R Vector
6.
Access elements of a vector
6.1.
1) Indexing with integer vector
6.2.
2) Indexing with a logical vector
6.3.
3) Indexing with a character vector
7.
Modifying the vector
8.
Vector Operation 
9.
Applications of vectors
10.
Frequently Asked Questions
10.1.
What is a vector in R with example?
10.2.
What are the 4 types of vectors in R?
10.3.
What is vector operation in R?
10.4.
Where is vector used?
11.
Conclusion
Last Updated: Mar 27, 2024
Medium

R Vector

Author Neha Chauhan
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

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!

vector in r programming

In this article, we will discuss how to create, modify and access a R Vector. 

Also see, Must Do Coding Questions

What is Vector in R Programming Language?

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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 elements to 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. 

Syntax

variable_name = seq( start_number, end_number, by, length.out) 

variable_name is the name of the variable in which the vector is stored. 

seq() is a function for creating a vector. 

start_number is an argument of the seq() function that indicates the first number of the sequence. 

last_number is an argument of the seq() function that indicates the last number of the sequence.

by is an argument of the seq() function that defines the step size. 

length is an argument of the seq() function that indicates the number of elements that should be there in the vector.  

Example 

Let’s create a vector with values - 1 to 10. 

Code

x <- seq(1, 10)

 

 Output

[1]  1  2  3  4  5  6  7  8  9 10

 

Code

y <- seq(1,2, by=0.5)

 

 Output

[1] 1.0 1.5 2.0

 

Code 

z <- seq(1, 10, by=0.3)

 

 Output

[1]  1.0  1.3  1.6  1.9  2.2  2.5  2.8  3.1  3.4  3.7  4.0  4.3  4.6  4.9  5.2  5.5

[17]  5.8  6.1  6.4  6.7  7.0  7.3  7.6  7.9  8.2  8.5  8.8  9.1  9.4  9.7 10.0

Also Read About, 8085 Microprocessor Pin Diagram

Types of R Vectors

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. 

Example 

Suppose we have the following vector named x -

 first second  third 

     1      2      3 

Run the following command to return the value 2. 

Code

x[“second”]

 

 Output

second 

     2

 

Run the following command to return both 2 and 3. 

Code

x[c(“second”,”third”)]

 

 Output

second  third 

     2      3


You can also read about mock interview.

Modifying the vector

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.

Example: c(1, 2, 3) + c(4, 5, 6) results in c(5, 7, 9).
 

2. Subtraction: Perform element-wise subtraction of two vectors of the same length.

Example: c(4, 5, 6) - c(1, 2, 3) results in c(3, 3, 3).
 

3. Multiplication: same as above, It performs element-wise multiplication of two vectors of the same length.

Example: c(2, 3, 4) * c(5, 6, 7) results in c(10, 18, 28).
 

4. Division: It also performs element-wise division of two vectors of the same length.

Example: c(10, 18, 28) / c(2, 3, 4) results in c(5, 6, 7).
 

5. Element-wise logical operations: It means performing element-wise logical operations on logical vectors.

Example: c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE) results in c(TRUE, FALSE, FALSE) (element-wise logical AND).

 

6. Scalar operations: It means performing scalar operations on a vector, applying a single value to each element.

Example: c(1, 2, 3) + 5 results in c(6, 7, 8).

 

7. Comparison operations: Return a logical vector by comparing the corresponding elements of two vectors.

Example: c(1, 2, 3) > c(2, 2, 2) results in c(FALSE, FALSE, TRUE).

 

8. Vector length: Use the length() function to find a vector's length.

Example: length(c(1, 2, 3)) returns 3.
 

9. Vector concatenation: Use the c() function to combine multiple vectors into a single vector.

Example: c(1, 2) + c(3, 4) results in c(1, 2, 3, 4).

Applications of vectors

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. 

Head to the Guided Path on the CodeStudio and upskill in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more courses.

If you want to Practice top Coding Problems, attempt mock tests, or read interview experiences, head to the CodeStudio, our practice platform.

We wish you Good Luck Please upvote our blog and help other ninjas grow.

Previous article
What is R Studio?
Next article
Matrices in R
Live masterclass