Thursday, April 13, 2023

R Tutorial Playlist - Vector

 Vector or collection in R is the basic type of array. It can hold any type of values except other vectors.

In order to create a vector type

a <- c(1, 2, 3, 4) or a <- c("1", "2", "3", "4") or a <- c(TRUE, TRUE, FALSE, TRUE)

So you see that in order to create vector, you have to use function c that stands for collection and elements in coma separated fashion.

Vector can't hold multiple types of values all at once. If you try to say something line a  <- c("1", 2, FALSE), you are going to end with a <- c("1", "2", "FALSE"), so in this case, all of values are going to be turned to strings.

If you try to add vector to a vector like in case a <- c(1, 2, 3, c(4, 5, 6)) you will end with single vector with elements 1, 2, 3, 4, 5, 6. So, if you try to add vector to a vector, elements of appending vector are going to be turned into elements of appended vector.

To append element to vector, use function append like b <- append(a, 36), and if you want to remove some element from vector use slicing:

  • b <- a[-5]  b is going to hold all of a elements except fifth.
  • b <- a[2:5] b is going to hold second, third, fourth, and fifth element of a.
  • b <- a[4] b is going to hold only fourth element of a. 
  • b <- a[3, 5] b is going to hold third and fifth element of a.
  • b <- a[-3, -5] b is going to hold all elements of a except third and fifth.
If you want to watch video tutorial about this subject, check the link below.



No comments:

Post a Comment