Week 7 Discussion - Introduction to R

by Corey Chu

Setup

x <- c(1, 3, 5, 7, 9)
y <- c(2, 3, 5, 7, 11, 13)
  1. x+1 Guess: each of the x vector’s values will be increased by 1 (2, 4, 6, 8, 10).
x+1
## [1]  2  4  6  8 10
  1. y*2 Guess: each of the y vector’s values will be doubled (4, 6, 10, 14, 22, 26).
y*2
## [1]  4  6 10 14 22 26
  1. length(x) and length(y) Guess: this will be the total number of values from both vectors (5+6 = 11)
length(x) + length(y)
## [1] 11
  1. x+y Guess: the shorter vector has five values, so for the first five values the corresponding numbers will be added together. Then x will loop back to the beginning to have its first value added to y’s sixth value (ultimately resulting in 3, 6, 10, 14, 20, 14)
x+y
## Warning in x + y: longer object length is not a multiple of shorter object
## length
## [1]  3  6 10 14 20 14
  1. sum(x>5) and sum(x[x>5]) Guess: x>5 is true when you only have the values 7 and 9, so the first sum is 7+9 = 16. I’m not too sure about the second one: is it (1+3+5+7+9)7 + (1+3+5+7+9)9, resulting in 400?
sum(x>5)
## [1] 2
sum(x[x>5])
## [1] 16

Response: I did not expect this. I figure sum(x>5) = 2 because it’s essentially asking to count how many elements fulfill the condition (two: 7 and 9). Is sum(x[x>5]) = 16 because it’s asking to sum all x elements for when x > 5?

  1. sum(x>5 | x< 3) # read | as ‘or’, & and ‘and’ Guess: There are three elements that are either greater than 5 (7, 9) or less than 3 (1).
sum(x>5 | x< 3)
## [1] 3
  1. y[3] Guess: This will select the third element of y (5)
y[3]
## [1] 5
  1. y[-3] Guess: This will select all elements of y except the third, so 2, 3, 7, 11, 13.
y[-3]
## [1]  2  3  7 11 13
  1. y[x] (What is NA?) Guess: this would select the first, third, fifth, seventh, and ninth elements of y; since y is only six elements long the seventh and ninth will be NA, or not available. The overall result should be 2, 5, 11, NA, NA.
y[x]
## [1]  2  5 11 NA NA
  1. y[y>=7] Guess: assuming x[x>5] means to identify the x values greater than 5, then y[y>=7] manes to identify the y values >=7, namely 7, 11, and 13
y[y>=7]
## [1]  7 11 13