# Introduction to R -- arithmetic operations on vectors etc. # Joe Felsenstein (May 2, 2011) # GS 560 ################################ # These R commands can be typed in, to practice R # Variables that are given names can be displayed by # simply typing their names. You can (and should) do # this to see what the results are. ################################ ################################ # Objects can be added, subtracted, etc. ################################ a <- 6 b <- 7 a+b a-b a*b a/b log(a) ################################ # Vectors and matrices can be added if they are the same length ################################ x <- c(101, 123, 98, 97.6) y <- c(72, 71, 73.6, 75) x+y x/y ################################ # functions of vectors or matrices are applied elementwise ################################ log(x) log(x+y) ################################ # When vectors are added, the shorter one is repeated as necessary # as long as longer one is a multiple of the length of the shorter # But there is an error message otherwise ################################ aa <- c(101, 97) # Try to figure out why these work bb <- c(23.7, 24, 26, 27) aa+bb bb+3 bb/aa ################################ # vectors of True/False can be made using operators like ">" ################################ cc <- bb > 25 ################################ # summing up the elements of a vector ################################ sum(bb) sum(bb*bb) ################################ # A teaser (more on this later): you can plot one vector against another # R easily makes all sorts of difficult plots ################################ xx <- x yy <- y plot(xx,yy) plot(xx,yy,type="line")