CSC121 - R Console Friday January 19th --------------------------- > # Vectors > > # One element vectors: the numbers we've been working with so far! > 2 [1] 2 > 54 [1] 54 > # Notice the [1] beside the first (and only) element in the vector > > # Let's make some multi-element vectors > # Use the c(...) function > c(3, 72) [1] 3 72 > c(83, 4, 938) [1] 83 4 938 > # Notice how the [1] is still there, beside the first element in each vector > # Let's try a longer vector to see when there's more than just [1] > c(234, 34234, 34534543, 453467567, 453534534, 5646456,345345345,35345345) [1] 234 34234 34534543 453467567 [5] 453534534 5646456 345345345 35345345 > c(234, 34234, 34534543, 453467567, 453534534, 5646456,345345345,35345345) [1] 234 34234 [3] 34534543 453467567 [5] 453534534 5646456 [7] 345345345 35345345 > c(234, 34234, 34534543, 453467567, 453534534, 5646456,345345345,35345345) [1] 234 34234 34534543 453467567 453534534 5646456 345345345 [8] 35345345 > # In this case, since the vector spans more than one line, each line starts with [X] where X is the index of the element directly to the right of it > > # Speaking of indexes, let's see how we can index a vector > # Let's assign a vector to a variable > v <- c(24, 5, 347, 97, 43) > v [1] 24 5 347 97 43 > v[1] [1] 24 > v[2] [1] 5 > # Now let's get a 'slice' of the vector > v[1:3] [1] 24 5 347 > # When we get a slice of the vector, we get back a NEW vector > slice <- v[1:3] > slice [1] 24 5 347 > v [1] 24 5 347 97 43 > length(v) [1] 5 > v[length(v)] [1] 43 > # length(v) evaluates to the length of the vector v, which is 5 > v[1:length(v)] [1] 24 5 347 97 43 > > # We can work with values from vectors like we have before > # Saving them to a variable > a <- v[2] > a [1] 5 > # passing them as arguments to a function > sqrt(v[4]) [1] 9.848858 > (v[3] + v[5]) / 2 [1] 195 > > # The type of the vector is the type of its elements > typeof(v) [1] "double" > b <- c(1, as.integer(2.3), 5) > typeof(b) [1] "double" > b [1] 1 2 5 > typeof(b[2]) [1] "double" > > # typeof() only takes one argument > typeof(b[2], b[1]) Error in typeof(b[2], b[1]) : unused argument (b[1]) > > # If everything in a vector is an integer, the type will be an integer > g <- c(as.integer(2), as.integer(5)) > typeof(g) [1] "integer" > > # You can change the type of the whole vector (we'll talk about vector manipulation next week) > as.integer(c(2,5)) [1] 2 5 > typeof(as.integer(c(2,5))) [1] "integer" > > > > #### Writing Distance Functions (can be found in distance_functions.R) > source('~/distance_functions.R') > > # Calling the function that doesn't use vectors > # Notice we need two arguments for every point! > DistanceWithoutVectors(-1, 2, 2, 6) [1] 5 > source('~/distance_functions.R') > > # With vectors, we can define a bunch of points as R vectors, and use our function to > # find the distance between them. > A <- c(-1, 2) > B <- c(2, 6) > DistanceWithVectors(A, B) [1] 5 >