One of the most significant objects in R is the vector. It is used to store multiple measures of the same type. The numeric vector is the most commonly used, and I will present below how to create a numerical vectors in R, and modify its elements with specific functions.
First, I create the vector 'age' containing different values/elements with the c() function as shown:
age <- c(20, 23, 25, 27, 30, 33)
To see the quantity and the type of the set of data in our vector, I use length() and typeof() function.
length(age)
## [1] 6
typeof(age)
## [1] "double"
From the output, the vector 'age' contains 6 elements and the type of vector is 'double', that means is identical to numeric.
To split a vector into chunks in R, I can use 'split', 'ceilin' and 'seq_along'; the number 2 in the code below presents the elements that will cantain each group.
split(age, ceiling(seq_along(age)/2))
## $`1`
## [1] 20 23
##
## $`2`
## [1] 25 27
##
## $`3`
## [1] 30 33
About the location and how each item is placed inside the vector I use:
age[3]
## [1] 25
age[2: 5]
## [1] 23 25 27 30
age[c(2, 5)]
## [1] 23 30
So in the third position of my vector '[3]' is number 25, '[2: 5]' shows the items from position 2 to 5 , and '[c(2, 5)]' indicates the elements located in position 2 and 5.
To create vectors for large variables is more tricky. So, instead of adding all the values to the c() function used previously, I buid 'x' vector with elements from number 20 to 50, as shown below:
x <- 20 : 50
or to make the vector more complex I apply sequence() and by() functions.
x1 <- seq(10, length = 30, by=2)
So '10' is the first value inside the vector, the following elements will be values adding 2 and the total number of elements will be 30.
Also, using the function rep() helps you to repeat the same elements inside a vector. It is placed the value(s) first and then how many times the value will be repeated.
x2 <- rep(10:20, 5)
x3 <- rep(10:20, each = 5, times = 3)
If I need to specifically repeat several values within vector, I put c() function inside the code, like below:
x4 <- rep(c(10,20,30), each = 5)
Feel free to leave any suggesions/comments.