Skip to content
Course Notes: Intermediate R
  • AI Chat
  • Code
  • Report
  • & and | Before you work your way through the next exercises, have a look at the following R expressions. All of them will evaluate to TRUE:

    TRUE & TRUE FALSE | TRUE 5 <= 5 & 2 < 3 3 < 4 | 7 < 6 Watch out: 3 < x < 7 to check if x is between 3 and 7 will not work; you'll need 3 < x & x < 7 for that.

    In this exercise, you'll be working with the last variable. This variable equals the last value of the linkedin vector that you've worked with previously. The linkedin vector represents the number of LinkedIn views your profile had in the last seven days, remember? Both the variables linkedin and last have been pre-defined for you. & and | (2) Like relational operators, logical operators work perfectly fine with vectors and matrices.

    Both the vectors linkedin and facebook are available again. Also a matrix - views - has been defined; its first and second row correspond to the linkedin and facebook vectors, respectively. Ready for some advanced queries to gain more insights into your social outreach? Blend it all together With the things you've learned by now, you're able to solve pretty cool problems.

    Instead of recording the number of views for your own LinkedIn profile, suppose you conducted a survey inside the company you're working for. You've asked every employee with a LinkedIn profile how many visits their profile has had over the past seven days. You stored the results in a data frame called li_df. This data frame is available in the workspace; type li_df in the console to check it out.

    The if statement Before diving into some exercises on the if statement, have another look at its syntax:

    if (condition) { expr } Remember your vectors with social profile views? Let's look at it from another angle. The medium variable gives information about the social website; the num_views variable denotes the actual number of views that particular medium had on the last day of your recordings. Both variables have been pre-defined for you. Add an else You can only use an else statement in combination with an if statement. The else statement does not require a condition; its corresponding code is simply run if all of the preceding conditions in the control structure are FALSE. Here's a recipe for its usage:

    if (condition) { expr1 } else { expr2 } It's important that the else keyword comes on the same line as the closing bracket of the if part!

    Both if statements that you coded in the previous exercises are already available to use. It's now up to you to extend them with the appropriate else statements! Customize further: else if The else if statement allows you to further customize your control structure. You can add as many else if statements as you like. Keep in mind that R ignores the remainder of the control structure once a condition has been found that is TRUE and the corresponding expressions have been executed. Here's an overview of the syntax to freshen your memory:

    if (condition1) { expr1 } else if (condition2) { expr2 } else if (condition3) { expr3 } else { expr4 } Again, It's important that the else if keywords comes on the same line as the closing bracket of the previous part of the control construct! Else if 2.0 You can do anything you want inside if-else constructs. You can even put in another set of conditional statements. Examine the following code chunk:

    if (number < 10) { if (number < 5) { result <- "extra small" } else { result <- "small" } } else if (number < 100) { result <- "medium" } else { result <- "large" } print(result) Have a look at the following statements:

    If number is set to 6, "small" gets printed to the console. If number is set to 100, R prints out "medium". If number is set to 4, "extra small" gets printed out to the console. If number is set to 2500, R will generate an error, as result will not be defined. Select the option that lists all the true statements.

    # Write and run code here
    # The linkedin and last variable are already defined for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    last <- tail(linkedin, 1)
    
    # Is last under 5 or above 10?
    5 < last | last > 10
    
    # Is last between 15 (exclusive) and 20 (inclusive)?
    last > 15 & last <= 20
    # The social data (linkedin, facebook, views) has been created for you
    
    # linkedin exceeds 10 but facebook below 10
    10 < linkedin & facebook < 10 
    
    # When were one or both visited at least 12 times?
    linkedin >= 12 | facebook >=12
    
    # When is views between 11 (exclusive) and 14 (inclusive)?
    views > 11 & views <=14
    # li_df is pre-loaded in your workspace
    li_df
    # Select the second column, named day2, from li_df: second
    second <- li_df$day2
    
    # Build a logical vector, TRUE if value in second is extreme: extremes
    extremes <- second > 25 | second < 5
    
    # Count the number of TRUEs in extremes
    sum (extremes)
    # The social data has been created for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    facebook <- c(17, 7, 5, 16, 8, 13, 14)
    views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)
    
    # When does views equal 13?
    views==13
    
    # When is views less than or equal to 14?
    views<=14
    # The linkedin and last variable are already defined for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    last <- tail(linkedin, 1)
    
    # Is last under 5 or above 10?
    5 < last | last > 10
    
    # Is last between 15 (exclusive) and 20 (inclusive)?
    last > 15 & last <= 20
    # The social data (linkedin, facebook, views) has been created for you
    
    # linkedin exceeds 10 but facebook below 10
    10 < linkedin & facebook < 10 
    
    # When were one or both visited at least 12 times?
    linkedin >= 12 | facebook >=12
    
    # When is views between 11 (exclusive) and 14 (inclusive)?
    views > 11 & views <=14
    # li_df is pre-loaded in your workspace
    li_df
    # Select the second column, named day2, from li_df: second
    second <- li_df$day2
    
    # Build a logical vector, TRUE if value in second is extreme: extremes
    extremes <- second > 25 | second < 5
    
    # Count the number of TRUEs in extremes
    sum (extremes)
    # Variables related to your last day of recordings
    medium <- "LinkedIn"
    num_views <- 14
    
    # Examine the if statement for medium
    if (medium == "LinkedIn") {
      print("Showing LinkedIn information")
    }
    
    # Write the if statement for num_views
    if(num_views>15) {print("You are popular!")}
    # Variables related to your last day of recordings
    medium <- "LinkedIn"
    num_views <- 14
    
    # Control structure for medium
    if (medium == "LinkedIn") {
      print("Showing LinkedIn information")
    } else {
      print("Unknown medium")
    }
    
    
    
    # Control structure for num_views
    if (num_views > 15) {
      print("You're popular!")
    } else { 
      print("Try to be more visible!")
    }
    # Variables related to your last day of recordings
    medium <- "LinkedIn"
    num_views <- 14
    
    # Control structure for medium
    if (medium == "LinkedIn") {
      print("Showing LinkedIn information")
    } else if (medium == "Facebook") {
      # Add code to print correct string when condition is TRUE
      print("Showing Facebook information")
    } else {
      print("Unknown medium")
    }
    
    # Control structure for num_views
    if (num_views > 15) {
      print("You're popular!")
    } else if (num_views <= 15 & num_views > 10) {
      # Add code to print correct string when condition is TRUE
      print("Your number of views is average")
    } else {
      print("Try to be more visible!")
    }
    # Variables related to your last day of recordings
    li <- 15
    fb <- 9
    
    # Code the control-flow construct
    if (li >=15 & fb >= 15) {
      sms <- 2 * (li + fb)
    } else if (li <10 & fb <10) {
      sms <- 0.5 * (li + fb)
    } else {
      sms <- li + fb
    }
    
    # Print the resulting sms to the console
    print(sms)
    # Initialize the speed variable
    speed <- 64
    
    # Code the while loop
    while (speed > 30) {
      print("Slow down!")
      speed <- speed -7
    }
    
    # Print out the speed variable
    speed
    # Initialize the speed variable
    speed <- 64
    
    # Extend/adapt the while loop
    while (speed > 30) {
      print(paste("Your speed is",speed))
      if (speed > 48) { 
        print("Slow down big time!")
        speed <- speed - 11
      } else {
        print("Slow down!")
        speed <- speed - 6
      }
    }
    # Initialize the speed variable
    speed <- 88
    
    while (speed > 30) {
      print(paste("Your speed is", speed))
      
      # Break the while loop when speed exceeds 80
      if (speed >80 ) {
      break
      }
      
      if (speed > 48) {
        print("Slow down big time!")
        speed <- speed - 11
      } else {
        print("Slow down!")
        speed <- speed - 6
      }
    }
    # Initialize i as 1 
    i <- 1
    
    # Code the while loop
    while (i <= 10) {
      print(3 * i)
      if (i %% 8 == 0) {
        break
      }
      i <- i + 1
    }
    # The linkedin vector has already been defined for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    
    # Loop version 1
    for (l in linkedin) {
        print(l)
    }
    
    
    
    # Loop version 2
    for (i in 1:length(linkedin)){
        print(linkedin[i])
    }
    # The nyc list is already specified
    nyc <- list(pop = 8405837, 
                boroughs = c("Manhattan", "Bronx", "Brooklyn", "Queens", "Staten Island"), 
                capital = FALSE)
    
    # Loop version 1
    for(n in nyc ) {
        print(n)
    }
    
    
    
    # Loop version 2
    for (n in 1:length(nyc)) {
        print(nyc[[n]])
    }
    # The tic-tac-toe matrix ttt has already been defined for you
    
    # define the double for loop
    for (i in 1:nrow(ttt)) {
      for (j in 1:ncol(ttt)) {
        print(paste("On row", i,  "and column", j, "the board contains", ttt[i, j]))
      }
    }
    # The linkedin vector has already been defined for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    
    # Code the for loop with conditionals
    for (li in linkedin) {
      if (li > 10) {
        print("You're popular!")
      } else {
      print("Be more visible!")
      }
      print(li)
    }
    # The linkedin vector has already been defined for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    
    # Adapt/extend the for loop
    for (li in linkedin) {
      if (li > 10) {
        print("You're popular!")
      } else {
        print("Be more visible!")
      }
      
      # Add if statement with break
      if(li > 16){
          print("This is ridiculous, I'm outta here!")
      break
        }
        
      
      # Add if statement with next
      if(li < 5){
        print("This is too embarrassing!")
        next
        }
      
      print(li)
    }
    # Pre-defined variables
    rquote <- "r's internals are irrefutably intriguing"
    chars <- strsplit(rquote, split = "")[[1]]
    help(sd)
    
    # Initialize rcount
    rcount <- 0 
    
    # Finish the for loop
    for (char in chars) {
      if(char=="r"){
        rcount <- rcount + 1
      }
      if(char=="u"){
        break
      }
    }
    
    # Print out rcount
    print(rcount)
    # Consult the documentation on the mean() function
    ?mean
    
    # Inspect the arguments of the mean() function
    args(mean)
    
    # The linkedin and facebook vectors have already been created for you
    linkedin <- c(16, 9, 13, 5, 2, 17, 14)
    facebook <- c(17, 7, 5, 16, 8, 13, 14)
    
    # Calculate average number of views
    avg_li <- mean(linkedin)
    avg_fb <- mean(facebook)
    
    # Inspect avg_li and avg_fb
    avg_li
    avg_fb
    Hidden output
    Spinner
    Data frameavailable as
    brands
    variable
    SELECT * FROM production.brands
    
    Spinner
    Data frameavailable as
    categories
    variable
    SELECT * FROM production.categories