#### Please work through vectors.R before you work through this script # chapter 2 of Braun and Murdoch # numbers that look exactly represented in decimal are not in binary n <- 1:10 1.25 * (n * 0.8) - n n <- (1:10)*1e30 1.25 * (n * 0.8) - n # density of numbers (on computers) is greatest near zero x <- 1:11 mean(x) var(x) sum( (x - mean(x))^2 )/10 (sum(x^2) - 11 * mean(x)^2 )/10 A <- 1e10 x <- 1:11 + A var(x) (sum(x^2) - 11 * mean(x)^2 )/10 # = 0 # lesson: first bring close to zero, then compute things further sum( (x - mean(x))^2 )/10 # Do not mix positive and negative indices. To see what happens, consider x=1:11 x[c(-2, 3)] #Error # The problem is that it is not clear what is to be extracted: # do we want the third element of x before or # after removing the second one? (x=2:4) y=c(3,2,1) x^y # elementwise raising to the power c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5) * 1:2 c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5) * 1:3 # if length of longer vec is not a multiple of shorter, it's a good bet # recycling was not intended x=c(0, 7, 8) x/x # 0/0 is undefined, so its NaN log(x) # -Inf 1/x # Inf (assumes approach is from positive side) length(integer(0)) is.null(integer(0)) is.integer(integer(0)) colors <- c("red", "yellow", "blue") numbers <- c(1, 2, 3) (colors.and.numbers <- data.frame(colors, numbers, more.numbers=c(4, 5, 6))) # looks like a matrix but its not. Matrices are vectors with .Dim attributes of # length 2, dataframes are lists where all the elements are named and have the same length. help.search("optimization") # finds help pages that include the work optimization ??optimization # same thing, less typing, easier to remember # or just google it with R a <- c(TRUE, FALSE, FALSE, TRUE) sum(a) # operation performed after converting FALSE to 0 and TRUE to 1. # i.e. this counts how many TRUEs are in the vector. x <- c(2,6,4,5,5,8,8,1,3,0) unique(x) duplicated(x) which(duplicated(x)) # positions of doubles x[duplicated(x)] # values of doubles x[!duplicated(x)] # set after doubles have been removed x[which(duplicated(x))] # positions of doubles