Data structure is the form of organizing and storing the data.
R supports five basic types of data structures
vector
matrix
list
data frame
factor
The data is stored in R as a vector.A vector is a sequence of data elements of the same type for example either integer or charcter.
The c() function can be used to create vectors .
A <- c(5, 6,2) ## Same Type
A
## [1] 5 6 2
Let’s see string Vector
apple <-c("red","pink","green")
apple
## [1] "red" "pink" "green"
age <- c(56,40,30,70,86)
age
## [1] 56 40 30 70 86
B <- c(TRUE, FALSE,TRUE) ## logical
B
## [1] TRUE FALSE TRUE
C <- c(T, T) ## logical
C
## [1] TRUE TRUE
D <- c("Aa", "Bb", "Cc") ## character
D
## [1] "Aa" "Bb" "Cc"
E <- c(1+0i, 2+4i) ## complex
E
## [1] 1+0i 2+4i
You can also use the vector() function to initialize vectors.
x <- vector("numeric", length = 6)
x
## [1] 0 0 0 0 0 0
x<- 7:9
x
## [1] 7 8 9
Y<- 6:-2
Y
## [1] 6 5 4 3 2 1 0 -1 -2
a1 <- c(1.7, “ba”) ## character
a2 <- c(TRUE, 9) ## numeric
a3 <- c(“V”, TRUE) ## character
Vectors can be combined via the function c
n = c(2, 3, 5)
s = c(“aa”, “bb”, “cc”, “dd”, “ee”)
c(n, s)
[1] “2” “3” “5” “aa” “bb” “cc” “dd” “ee”
Arithmetic operations of vectors are performed member-by-member.
For example, suppose we have two vectors x and y
x = c(1, 5, 5, 8 ,9)
y = c(1, 3, 4, 8, 20)
4 * x
[1] 4 20 20 32 36
x + y
[1] 2 8 9 16 29
For subtraction, multiplication and division, we get new vectors via memberwise operations.
x - y [1] 0 2 1 0 7
x * y [1] 1 15 64 180
x / y [1] 1.000000 1.666667 1.250000 1.000000 0.450000
If two vectors are of unequal length, the shorter one will be recycled in order to match the longer vector.
a = c(1, 2, 3)
b = c(6, 7, 8, 18, 9 ,20)
a + b
[1] 7 9 11 19 11 23
We retrieve values in a vector by declaring an index inside a single square bracket “[]” operator.
>x= c(“A”, “B”, “D”, “A”, “F”)
>x[3]
[1] “D”
Out-of-Range Index
If an index is out-of-range, a missing value will be reported via the symbol NA.
x[12]
[1] NA
vec1 <- c(1, 8, 10) vec2 <- c(0, 5, 7)
vec1 == vec2 # [1] FALSE TRUE FALSE
vec_one < vec_two # [1] FALSE FALSE TRUE
vec_one == 1 # [1] TRUE FALSE FALSE
V1 <- c(‘AA’, ‘BB’, ‘CC’)
cat(V1, sep=“”)
# # AA # BB # CC
Sorting of vectors can be done using the sort() function. By default, it sorts in ascending order. To sort in descending order we can pass decreasing=TURE.
x >- 7 2 3 6
sort in ascending order
sort(x)
[1] 2 3 6 7
sort in descending order
sort(x, decreasing=TRUE)
[1] 7 6 3 2
vector remains unaffected
> x [1] 7 2 3 6
(1)R Programming For Beginners Part 1 https://www.youtube.com/watch?v=DmX5TW473BA
(2)R tutorial by examples:Data Frame https://rpubs.com/sheikh/data_frame (3)Data Manipulation with dplyr using Covid19 Data https://rpubs.com/sheikh/dplyr (4)R Tutorial:Graphs using qplot https://rpubs.com/sheikh/qplot
(5)title: “R Data Structure: Vector”
https://rpubs.com/sheikh/vector