R Objects and Commands

3 types of R objects, vector, data frame, and matrix.

By Montaque Reynolds

January 26, 2021

Vectors

Contains a set of values. These include vec_num, number vector and vec_char whwhich is a character vector. c() combines the elements of a vector and <- assigns a vector to a variable.

vec_num <- c(1, 5, 6, 3)
vec_num
## [1] 1 5 6 3
vec_char <- c("apple", "banana", "mandarin", "melon")
vec_char
## [1] "apple"    "banana"   "mandarin" "melon"

Once we have created a vector, we can extract its elements using the [] operator. For instance, you can extract the first element [1],

vec_char <- c("apple", "banana", "mandarin", "melon")
vec_char[1]
## [1] "apple"

or the first 3 elements [1:3].

vec_char[1:3]
## [1] "apple"    "banana"   "mandarin"

Some functions

Arithmetic, Multiplication, Division, Subtraction

vec_num2 <- vec_num + 2
vec_num3 <- vec_num / 2
vec_num4 <- vec_num * 4
vec_num5 <- vec_num - 1

vec_num
## [1] 1 5 6 3
# Addition

vec_num2
## [1] 3 7 8 5
# Division

vec_num3
## [1] 0.5 2.5 3.0 1.5
# Multiplication

vec_num4
## [1]  4 20 24 12
# Subtraction

vec_num5
## [1] 0 4 5 2

Comparing vectors using relational operators (returns TRUE or FALSE)

vec_logi_gt5 <- vec_num >= 5
vec_logi_gt5
## [1] FALSE  TRUE  TRUE FALSE

We can do this using the equality operator only on character vectors

vec_logi_apple <- vec_char == "apple"
vec_logi_apple
## [1]  TRUE FALSE FALSE FALSE

We can also concatenate vector elements using paste().

vec_char2 <- paste(c("red", "yellow", "orange", "green"), vec_char)
print(vec_char2)
## [1] "red apple"       "yellow banana"   "orange mandarin" "green melon"

We can also set names to the elements of a numeric vector

names(vec_num) <- vec_char
print(vec_num)
##    apple   banana mandarin    melon 
##        1        5        6        3

Data Frames

Data Frames combine multiple vectors to construct a data set. However, though vectors can be of different types, they can only be combined if they have the same lengths.

dat_fruit <- data.frame(name = vec_char, count = vec_num)
print(dat_fruit)
##              name count
## apple       apple     1
## banana     banana     5
## mandarin mandarin     6
## melon       melon     3