############## # Section 9 ############## # Extracting subsets of a column data(state) tryit <- state.name[50:46] tryit match(tryit,state.name) tryit %in% state.name tryit2 <- c("Georgia", "Florida", "Guam") tryit2 %in% state.name state.name[-(31:40)] #Extracting subsets of an array bigmat<-matrix(1:100,nr=10,nc=10) newmat <- bigmat[-1,] newmat <- bigmat[,2:10] newmat <- bigmat[1:3,1:3] newmat <- bigmat[,c(2,8,6)] tristate.region <- state.x77[c("South Carolina","Georgia", "North Carolina"),] tristate.region #Logical extraction south.region <- state.x77[state.region=="South",] south.region my.logic <- state.x77[,2] > 5000 rich.states <- state.x77[my.logic,] #Self-referential logical extraction x=rnorm(10) x[x>0] x>0 which(x>0) x[which(x>0)] SouthHighIllit=state.x77[(state.region=="South")&(state.x77[,"Illiteracy"]>2.0),] SouthHighIllit #Ordering a variable ord <- order(state.area) ord state.name[ord] ord <- rev(order(state.area)) state.name[ord] # Other ways to reverse ordering: ord <- order(-state.area) ord <- order(state.area, decreasing=TRUE) #Ordering an entire array by a single column Population <- state.x77[,"Population"] ord <- rev(order(Population)) state.x77.popsorted <- state.x77[ord,] state.x77.popsorted #Shortcut: state.x77.popsorted=state.x77[rev(order(state.x77[,"Population"])),] state.x77.popsorted #Ordering by two variables state.dfr <- data.frame(state.name,state.region,state.x77) ord <- order(as.character(state.region), (-Population)) state.dfr<-state.dfr[ord,] state.dfr # Simple sorting of a single vector: Population sort(Population) sort(Population,decreasing=TRUE)