stat405

Style drills

Rewrite each code block to comply with the class style guide.

  1. x < - c( 1,-2,3,-4,5,NA )
      y < - x * - 1
      y[ y>0 ]
    
    x <- c(1, -2, 3, -4, 5, NA)
    y <- x * -1
    y[y > 0]
    
  2. n = 1
    mycondition <- round (runif (1,0,1,))
    if( mycondition ) {
        n <- n + 1
        print(paste("n =" , n , sep=" "))
    } else {
    print("false")
    }
    n <- 1
    my_condition <- round(runif(1, 0, 1))
    if (my_condition) {
      n <- n + 1
      print(paste("n =", n, sep = " "))
    } else {
      print("false")
    }
  3. # create a sequence from 1 to 50
    z <- seq(1,50)
    
    # test whether an observation is even
    even <- z%%2 = = 0
    
    # subset z by the test above
    z = z [even]
    
    # plot a histogram
    library( ggplot2 )
    qplot (z, geom="histogram", binwidth=1)
    z <- seq(1, 50)
    
    # test whether an observation is even
    even <- z %% 2 == 0
    
    z <- z[even]
    
    library(ggplot2)
    qplot(z, geom = "histogram", binwidth = 1)
  4. mat <- matrix( c( 34, 23, 53, 6, 78, 93, 12, 41, 99 ) ,nrow = 3)
    df <- as.data.frame (mat)
    names( df ) <- c("score_given_to_car_on_driving_test", 
     "score.given.to.van.on.driving.test", 
      "score-given-to-truck-on-driving-test")
    mat <- matrix(c(34, 23, 53, 6, 78, 93, 12, 41, 99), nrow = 3)
    df <- as.data.frame(mat)
    names(df) <- c("car", "van", "truck")
  5. library( ggplot2 )
      head(mpg)
    second_version_of_mpg <- mpg[ mpg$cyl = 6,]
    second_version_of_mpg$class <- as.character(mpg2$class)
    qplot(cty, hwy, data=second_version_of_mpg, geom="point", color=class ) +  geom_smooth( method = "lm", se=FALSE ) + opts (title="City vs. Highway MPG" )
    library(ggplot2)
    head(mpg)
    mpg2 <- mpg[mpg$cyl == 6, ]
    mpg2$class <- as.character(mpg2$class)
    qplot(cty, hwy, data = mpg2, geom = "point", color = class) + 
      geom_smooth(method = "lm", se = FALSE) + 
      opts(title = "City vs. Highway MPG")
  6. mean <- function(x) {
    sum(x)/length(x)
    }
      
    mean <- function(x) {
      sum(x) / length(x)
    }