Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Created February 9, 2016 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aravindhebbali/d3e1b62db09cfc875ad7 to your computer and use it in GitHub Desktop.
Save aravindhebbali/d3e1b62db09cfc875ad7 to your computer and use it in GitHub Desktop.
R Data Structures: Introduction to Vectors - Part 2
# vector coercion
# case 1: create a vector of different data types
vect1 <- c(1.5, 1L, 'one', TRUE)
vect1
# test data type
class(vect1)
# case 2: create a vector of different data types excluding character
vect2 <- c(1.5, 1L, TRUE)
vect2
# test data type
class(vect2)
# case 3: create a vector of integer and logical data
vect3 <- c(1L, TRUE)
vect3
# test data type
class(vect3)
# handling missing data
# create a vector with missing data
mis_vect <- c(1:3, NA, 6:4)
mis_vect
# test for missing data
is.na(mis_vect)
complete.cases(mis_vect)
# omit missing data
vect1 <- c(1, 4, 2, NA, 9)
na.omit(vect1)
# exclude missing data
mis_vect
# compute mean with missing data
mean(mis_vect)
# compute mean after excluding missing data
mean(mis_vect, na.rm = TRUE)
# subset vectors
# index operator
vect1 <- sample(10)
vect1
# return value at index 3
vect1[3]
# return value at index 7
vect1[7]
# out of range index
vect1 <- sample(10)
vect1
# return value at index 0
vect1[0]
# return value at index 11
vect1[11]
# negative index
vect1 <- sample(10)
vect1
# drop value at index 3
vect1[-3]
# drop value at index 8
vect1[-8]
# subset multiple elements
vect1 <- sample(10)
vect1
# return all the elements
vect1[]
# return the first 5 values
vect1[1:5]
# returns error
vect[:5]
# return all elements from the 5th
end <- length(vect1)
vect1[5:end]
# return 2nd, 5th and 7th element
vect1[c(2, 5, 7)]
# another method
select <- c(2, 5, 7)
vect1[select]
# subset named elements
named_vect <- c(score1 = 8, score2 = 5, score3 = 6, score4 = 9)
named_vect['score3']
# returns error
named_vect[score3]
# subset using logical values
vect1 <- sample(10)
vect1
# returns all elements
vect1[TRUE]
# returns empty vetor
vect1[FALSE]
# returns elements at odd positions
vect1[c(TRUE, FALSE)]
# returns elements at even position
vect1[c(FALSE, TRUE)]
# subset using logical expressions
vect1 <- sample(10)
vect1
# return elements greater than 5
vect1[vect1 > 5]
# return elements lesser than or equal to 8
vect1[vect1 <= 8]
# return all elements less than 8 or divisible by 3
vect1[vect1 < 8 | (vect1 %% 3 == 0)]
# return all elements less than 7 and divisible by 2
vect1[vect1 < 7 & (vect1 %% 2 == 0)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment