############# # Section 8 ############# #Logical vectors data(mtcars) guzzlers <- (mtcars$mpg < 20) guzzlers names(guzzlers) <- row.names(mtcars) guzzlers small_engines=(mtcars$cyl==4) names(small_engines)=row.names(mtcars) small_engines mtcars$mpg (mtcars$mpg == 21) (mtcars$mpg != 21) (mtcars$mpg >= 21) (mtcars$mpg <= 21) (mtcars$mpg <= 1:32) (mtcars$mpg <= 21:22) eq21 <- (mtcars$mpg == 21) eq21 !eq21 #Logical operators eq21 & guzzlers eq21 | guzzlers all(eq21) any(eq21) eq21 sum(eq21) mean(eq21) # Note there are '&&' and '||" logical operators which are not as generally useful # From the help file: The longer form evaluates left to right examining only the first element of each vector. # Evaluation proceeds only until the result is determined. # The longer form is appropriate for programming control-flow and typically preferred in if clauses. # Handling missing values (NAs) x=c(10,NA,20) x<15 x>15 sum(x>15) sum(x>15,na.rm=T) guzzlers&small_engines guzzlers|small_engines guzzlers&!small_engines any(mtcars$mpg>40) a <- sqrt(2) a * a == 2 a * a - 2 all.equal(a*a, 2) #The if statement x=rnorm(1) y=rnorm(1) x>y if(x>y) {z=x^2; w=30*x} else {z=30*x; w=x^2} if(x>y) { z=x^2 w=30*x } else { z=30*x w=x^2 } #Look at z and w closely--they're based only on x[1] vs. y[1] x=rnorm(5) y=rnorm(5) x>y if(x>y) {z=x^2; w=30*x} else {z=30*x; w=x^2} cbind(x,y,z,w) # use ifelse for elementwise conditional logic: x=rnorm(5) y=rnorm(5) x>y z = ifelse(test = x>y, yes = x^2, no = 30*x) #explicitly including argument names w = ifelse(x>y, 30*x, x^2) cbind(x,y,z,w) # look at "conditional.txt" file #The ifelse statement matwithNAs <- matrix(c(3,6,NA,7,1,5,NA,NA,10), nrow=3,ncol=3, byrow=T) mat.replace <- ifelse(is.na(matwithNAs), 0, matwithNAs) mmp.truncated <-ifelse(mtcars$mpg>20,20,mtcars$mpg)