Vectors in R Programming and its Types , Common Operations

 In R programming, a vector is a one-dimensional array that can hold elements of the same data type. It is a fundamental data structure in R and is used extensively in data analysis and manipulation.

The syntax for creating a vector is:

vector_name <- c(element1, element2, ...)

Here,

l    vector_name is the name of the vector and element1, element2, and so on are the elements that you want to store in the vector.

l    The c() function is used to concatenate the elements into a vector.


Ø   There are several types of vectors in R:

In R, there are four types of vectors: numeric, character, logical, and integer. Each type of vector can hold data of a specific data type.


a.         Numeric vectors: Numeric vectors hold numeric data such as integers and floating-point numbers.

Here is an example:                                 numeric_vector <- c(1, 2, 3.5, 4.2)


b.         Character vectors: Character vectors hold text data.

Here is an example:                               character_vector <- c("apple", "banana", "orange")


c.         Logical vectors: Logical vectors hold logical data, which can be either TRUE or FALSE.

Here is an example:                                 logical_vector <- c(TRUE, FALSE, TRUE, TRUE)


d.         Integer vectors: Integer vectors hold integer data.

Here is an example:                                 integer_vector <- c(1L, 2L, 3L, 4L)


Note that the L after each number indicates that it is an integer.


Ø   Operations on  Vectors:


l    Creating / declaring  a Vector

Let's create a numeric vector named my_vector that contains the values 1, 2, 3, and 4:

my_vector <- c(1, 2, 3, 4)


l    Accessing Elements of a Vector

You can access individual elements of a vector using square brackets [].


For example, to access the second element of my_vector, you can use:

my_vector[2]

This will return 2, which is the second element in the my_vector.


l    Modifying Elements of a Vector

To modify an element of a vector, you can assign a new value to the element using the square bracket notation.


For example, to change the third element of my_vector to 10, you can use:

my_vector[3] <- 10

Now, my_vector will be [1, 2, 10, 4].


l    Deleting Elements of a Vector

You can delete elements of a vector using the negative index.


For example, to delete the third element of my_vector, you can use:

my_vector <- my_vector[-3]

Now, my_vector will be [1, 2, 4].


l    Sorting Elements of a Vector

You can sort the elements of a vector using the sort() function.


For example, to sort the elements of my_vector in ascending order, you can use:

sort(my_vector)

This will return [1, 2, 4].

No comments:

Post a Comment

R Programming Language

Data Analytics and the key concepts and techniques of R language

Data Analytics  Data analytics is the process of examining, cleaning, transforming, and modeling data to extract useful information and insi...