#### "All the examples" from ./R-intro.texi #### -- in a way that this should be(come) an executable script. ## 2. Simple Manipulations x <- c(10.4, 5.6, 3.1, 6.4, 21.7) 1/x # put vectors together y <- c(x, 0, x) #Perform operations on vectors sqrt(x) ###-- 2.3 .. regular sequences 1:30 n <- 10 1:n-1 1:(n-1) 30:1 seq(2,10) s3 <- seq(-5, 5, by=.2) s4 <- seq(length=51, from=-5, by=.2) all.equal(s3,s4) s5 <- rep(x, times=5) s6 <- rep(x, each=5) temp <- x > 13 z <- c(1:3,NA); ind <- is.na(z) 0/0 Inf - Inf labs <- paste(c("X","Y"), 1:10, sep="") labs x <- c(x, 9:12)# long enough: x[1:10] y <- x[-(1:5)] y fruit <- c(5, 10, 1, 20) names(fruit) <- c("orange", "banana", "apple", "peach") fruit lunch <- fruit[c("apple","orange")] lunch ###--------------- z <- 0:9 digits <- as.character(z) digits d <- as.integer(digits) all.equal(z, d) alpha <- 10*(1:10) alpha <- alpha[2 * 1:5] alpha winter <- data.frame(temp = c(-1,3,2,-2), cat = rep(c("A","B"), 2)) winter ###------------ Ordered and unordered factors -------- state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa", "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas", "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa", "sa", "act", "nsw", "vic", "vic", "act") statef <- factor(state) statef levels(statef) incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56, 61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46, 59, 46, 58, NA) incmeans <- tapply(incomes, statef, mean, na.rm=T) # similar to the 'aggregate' function) incmeans stderr <- function(x) sqrt(var(x)/length(x)) incster <- tapply(incomes, statef, stderr) incster ### apply functions # there are a family of apply functions X<-matrix(rnorm(30), nrow=5, ncol=6) X apply(X,2,sum) # sums columns apply(X,1,mean) # row means # apply A<-matrix(1:9, 3,3) B<-matrix(4:15, 4,3) C<-matrix(8:10, 3,2) MyList<-list(A,B,C) # display the list lapply(MyList,"[", ,1) # Extract first column of each matrix lapply(MyList,"[", 1,) # Extract first row of each matrix sapply(MyList, mean) # return the mean of each list object ###--- @chapter 6. Lists and data frames Lst <- list(name="Fred", wife="Mary", no.children=3, child.ages=c(4,7,9)) Lst$name Lst$wife Lst$child.ages[1] x <- "name" ; Lst[[x]] ## @section 6.2 Constructing and modifying lists ## Mat <- cbind(1, 2:4) ## Lst$matrix <- Mat Lst ## @section 6.3 Data frames accountants <- data.frame(home=statef, loot=incomes) ## MM: add the next lines to R-intro.texi ! accountants str(accountants) ## .......... # do some basic plots hist(accountants$loot) plot(accountants$home, accountants$loot,xlab="State", ylab="Income") # produces a boxplot as 'home' is a factor