R Vectors

A Vector in the R programming language are items of the same datatype. In this lesson, we will learn how to create a Vector and work on some Vector operations:

  • Create a Vector
  • Access Vector Items
  • Vector Length
  • Sort Vector Items
  • Add Vectors
  • Subtract Vectors
  • Multiply Vectors

Create a Vector

The c() method is used to create a Vector in R. The Vector items are separated by comma. Let us see the examples to create a Vector with:

  • Numerical Values
  • Numerical Values in Sequence
  • String values
  • Boolean values

Let us create a Vector, beginning with numerical values.

Create a Vector with numerical values

Use the c() function to create a vector of numerical values in the R programming language:

Output

Create a Vector with numerical values in a sequence

The : operator is used in R to create a vector with numerical values in sequence:

Output

Create a Vector with string values

We will use the c() function to create a vector with string values:

Output

Create a Vector with boolean values

We will use the c() function to create a vector with boolean values. The boolean includes only TRUE and FALSE values:

Output

Access Vector Items

Use the [] brackets to access vector items i.e., elements of an R vector. Just set the position number of the element you want to fetch. Follow the below syntax:

Output

In the above example, we have accessed the 3rd item since we have set position 3.

Vector Length

The length() function is used in the R programming language to get the vector length. Let us see an example:

Output

Sort Vector Items

The sort() function is used in the R programming language to sort the vector items. Let us see an example:

Output

Add Vectors

In the below example, we will add two vectors in the R programming language:

Output

Subtract Vectors

In the below example, we will subtract two vectors in the R programming language:

Output

Multiply Vectors

In the below example, we will multiply vectors in the R programming language:

Output

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

R Arrays
R Lists
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading