Created
February 9, 2016 11:16
-
-
Save aravindhebbali/ceaa3562547eb412a592 to your computer and use it in GitHub Desktop.
R Data Structures: Introduction to Vectors - Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# create a numeric vector using c() | |
num_vect <- c(1, 2.3, 5) | |
num_vect | |
# test the data structure | |
is.vector(num_vect) | |
# test the data type | |
class(num_vect) | |
# create vector using colon | |
vect1 <- 1:10 | |
vect1 | |
# create a vector using replicate function | |
vect2 <- rep(1:5, 2) | |
vect2 | |
# create a function using the sequence function | |
vect3 <- seq(10) | |
vect3 | |
# integer vector | |
int_vect <- c(1L, 2L, 3L) | |
int_vect | |
# test data type | |
class(int_vect) | |
# create integer vector using colon | |
vect1 <- 1L:10L | |
vect1 | |
# create integer a vector using replicate function | |
vect2 <- rep(1L:5L, 2) | |
vect2 | |
# create integer a function using the sequence function | |
vect3 <- seq(10L) | |
vect3 | |
# character vector | |
greetings <- c('good', 'morning') | |
greetings | |
# test data type | |
class(greetings) | |
# error if elements not enclosed in quotes | |
name <- c(Jovial, Mann) | |
# logical vectors | |
vect_logic <- c(TRUE, FALSE, FALSE, TRUE, TRUE) | |
vect_logic | |
# test data type | |
class(vect_logic) | |
# coerce integer vector to type logical | |
int_vect <- rep(0:1, 3) | |
int_vect | |
log_vect <- as.logical(int_vect) | |
log_vect | |
# naming vector elements | |
# method 1 | |
# create the vector | |
vect1 <- c(1, 2, 3) | |
# specify the names of the elements | |
names(vect1) <- c('One', 'Two', 'Three') | |
vect1 | |
# method 2 | |
# specify name of the elements while creating the vector | |
vect2 <- c(One = 1, Two = 2, Three = 3) | |
vect2 | |
names(vect2) | |
# vector operations | |
# case 1: vectors of equal length | |
vect1 <- c(1, 3, 8, 4) | |
vect2 <- c(2, 7, 1 , 9) | |
# vector addition | |
vect1 + vect2 | |
# vector subtraction | |
vect1 - vect2 | |
# vector multiplication | |
vect1 * vect2 | |
# vector division | |
vect1 / vect2 | |
# case 2: vectors of unequal length | |
vect1 <- c(1, 8, 5, 2) | |
vect2 <- c(2, 7) | |
# vector addition | |
vect1 + vect2 | |
# vector subtraction | |
vect1 - vect2 | |
# vector multiplication | |
vect1 * vect2 | |
# vector division | |
vect1 / vect2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment