Introduction to Vectors

In R, a vector is a sequence of data elements of the same basic type. The c() function is used to create a vector.

# A numeric vector
numeric_vector <- c(1, 2, 3, 4, 5)
print(numeric_vector)
## [1] 1 2 3 4 5
# A character vector
character_vector <- c("a", "b", "c", "d", "e")
print(character_vector)
## [1] "a" "b" "c" "d" "e"

Exercises

  1. Create a numeric vector named my_numeric_vector with the numbers 10, 20, 30, 40, and 50.
# Your code here
my_numeric_vector<- c(10,20,30,40,50)
print(my_numeric_vector)
## [1] 10 20 30 40 50
  1. Create a character vector named my_character_vector with the names of your three favorite colors.
# Your code here
my_character_vector<- c("orange","mustard","beige")
print(my_character_vector)
## [1] "orange"  "mustard" "beige"
  1. Get the length of my_numeric_vector.
# Your code here
length(my_numeric_vector)
## [1] 5
  1. Create a vector containing a numeric, a logical, and a character element. What is the type of the resulting vector?
# Your code here
v <- c(10,TRUE,"Mona")
 #print the vector
print(v)
## [1] "10"   "TRUE" "Mona"
# Print the class/type
 class(v)
## [1] "character"
 #check internal storage type
 typeof(v)
## [1] "character"
  1. Add the following two vectors: c(1, 2, 3) and c(4, 5, 6).
# Your code here
x<-c(1,2,3)
y<-c(4,5,6)
z<-c(x,y)
print(z)
## [1] 1 2 3 4 5 6
  1. What happens if you add two vectors of different lengths? Try adding c(1, 2, 3) and c(4, 5).
# Your code here
x<-c(1,2,3)
y<-c(4,5)
print(x+y)
## Warning in x + y: longer object length is not a multiple of shorter object
## length
## [1] 5 7 7
  1. Create an empty vector named my_results. Then, append the number 10 to it.
# Your code here
my_results<-c()
my_results<-c(my_results,10)
print(my_results)
## [1] 10
  1. Given the vector c(1, 5, 2, 8, 4, NA), find the sum, mean, and product of the vector. Then, do the same but ignore the NA value.
# Your code here
x<-c(1,5,2,8,4,NA)
sum(x)
## [1] NA
mean(x)
## [1] NA
prod(x)
## [1] NA
#ignore NA
sum(x,na.rm =TRUE)
## [1] 20
mean(x,na.rm = TRUE)
## [1] 4
prod(x,na.rm = TRUE)
## [1] 320
  1. Given the vector c(1, 5, 2, 8, 4), find the minimum and maximum values.
# Your code here
x<- c(1,5,2,8,4)
min(x)
## [1] 1
max(x)
## [1] 8
  1. Sort the vector c(1, 5, 2, 8, 4) in ascending and descending order.
# Your code here
x<-c(1,5,2,8,4)
#Ascending order
sort(x)
## [1] 1 2 4 5 8
#descending Order
sort(x,decreasing=TRUE)
## [1] 8 5 4 2 1
  1. Check if the number 5 is present in the vector c(1, 5, 2, 8, 4).
# Your code here
x<-c(1,5,2,8,4)
5%in%x
## [1] TRUE

Solutions

Click here for the solutions