The most basic form of comparison is equality. Let’s briefly recap its syntax. The following statements all evaluate to TRUE (feel free to try them out in the console).
Since TRUE coerces to 1 under the hood, TRUE == 1 evaluates to TRUE. Make sure not to mix up == (comparison) and = (assignment), == is what need to check the equality of R objects.
Apart from equality operators, I also introduced the less than and greater than operators: < and >. You can also add an equal sign to express less than or equal to or greater than or equal to, respectively. Have a look at the following R expressions, that all evaluate to FALSE:
(1 + 2) > 4 “dog” < “Cats” TRUE <= FALSE Remember that for string comparison, R determines the greater than relationship based on alphabetical order. Also, keep in mind that TRUE corresponds to 1 in R, and FALSE coerces to 0 behind the scenes. Therefore, FALSE < TRUE is TRUE.
INSTRUCTIONS Write R expressions to check whether:
HINT A correct answer to the second instruction would be: “raining” <= “raining dogs”
You are already aware that R is very good with vectors. Without having to change anything about the syntax, R’s relational operators also work on vectors.
Let’s go back to the example that was started in the video. You want to figure out whether your activity on social media platforms have paid off and decide to look at your results for LinkedIn and Facebook. The sample code in the editor initializes the vectors linkedin and facebook. Each of the vectors contains the number of profile views your LinkedIn and Facebook profiles had over the last seven days.
INSTRUCTIONS
Using relational operators, find a logical answer, i.e. TRUE or FALSE, for the following questions:
HINT Let’s get you up to speed with a comparable example. To see when your LinkedIn profile was viewed more than 10 times, use:
linkedin > 10
R’s ability to deal with different data structures for comparisons does not stop at vectors. Matrices and relational operators also work together seamlessly!
Instead of in vectors (as in the previous exercise), the LinkedIn and Facebook data is now stored in a matrix called views. The first row contains the LinkedIn information; the second row the Facebook information. The original vectors facebook and linkedin are still available as well.
INSTRUCTIONS:
Using the relational operators you’ve learned so far, try to discover the following:
When were the views exactly equal to 13? Use the views matrix to return a logical matrix.
For which days were the number of views less than or equal to 14? Again, have R return a logical matrix.
HINT To see when views equals 13, you can use the == operator, just like you did for vectors!
This exercise concludes the part on comparators. Now that you know how to query the relation between R objects, the next step will be to use the results to alter the behavior of your programs.
Before you work your way through the next exercises, have a look at the following R expressions. All of them will evaluate to TRUE:
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 already been defined in the editor.
INSTRUCTIONS:
Write R expressions to solve the following questions concerning the variable last:
HINT:
In the last instruction, you should use the & operator twice and the | operator once. Use parentheses to make sure that the order of execution is correct!
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?
INSTRUCTIONS:
When did LinkedIn views exceed 10 and did Facebook views fail to reach 10 for a particular day? Use the linkedin and facebook vectors. When were one or both of your LinkedIn and Facebook profiles visited at least 12 times? When is the views matrix equal to a number between 11 and 14, excluding 11 and including 14?
HINT: Be sure to using a single & and a single | in these exercises! && and || will only examine the first element of your vector or matrix.
You’ll have noticed how easy it is to use logical operators to vectors and matrices. What do these results tell us? The third day of the recordings was the only day where your LinkedIn profile was visited more than 10 times, while your Facebook profile wasn’t. Can you draw similar conclusions for the other results?
Reverse the result: ! On top of the & and | operators, you also learned about the ! operator, which negates a logical value. To refresh your memory, here are some R expressions that use !. They all evaluate to FALSE:
!!FALSE What would the following set of R expressions return?
!(!(x < 4) & !!!(y > 12))
With the things you’ve learned by now, you’re able to solve pretty cool problems. 需要构建数据集才能work
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.
INSTRUCTIONS: Select the entire second column, named day2, from the li_df data frame as a vector and assign it to second. Use second to create a logical vector, that contains TRUE if the corresponding number of views is strictly greater than 25 or strictly lower than 5 and FALSE otherwise. Store this logical vector as extremes. Use sum() on the extremes vector to calculate the number of TRUEs in extremes (i.e. to calculate the number of employees that are either very popular or very low-profile). Simply print this number to the console.
HINT: You can select the data for the second day with li_df$day2. Use a combination of relational and logical operators for the second instruction: >, < and |. sum(extremes) will count all the TRUEs in extremes.
HINT: You can select the data for the second day with li_df$day2. Use a combination of relational and logical operators for the second instruction: >, < and |. sum(extremes) will count all the TRUEs in extremes.
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 these variables have already been defined in the editor.
INSTRUCTIONS: Examine the if statement that prints out “Showing LinkedIn information” if the medium variable equals “LinkedIn”. Code an if statement that prints “You’re popular!” to the console if the num_views variable exceeds 15.
HINT Use the print() function to print things to the console output. Have another look at the video if you are not sure how to write your own if statements.
HINT Use the print() function to print things to the console output. Have another look at the video if you are not sure how to write your own if statements.Try to see what happens if you change the medium and num_views variables and run your code again. Let’s further customize these if statements in the next exercise.
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 in the editor. It’s now up to you to extend them with the appropriate else statements!
INSTRUCTIONS: Add an else statement to both control structures, such that
HINT To add an else statement, change:
if () { } to
if () { } else { } Up to you to fill in the !You also had Facebook information available, remember? Time to add some more statements to our control structures using else if! 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!
INSTRUCTIONS:
Add code to both control structures such that:
HINT: For both instructions, just keep the if, else if and else statements that are already available; just add the appropriate code within the else if statement.
Have another look at the second control structure. Because R abandons the control flow as soon as it finds a condition that is met, you can simplify the condition for the else if part in the second construct to num_views > 10
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.
In this exercise, you will combine everything that you’ve learned so far: relational operators, logical operators and control constructs. You’ll need it all!
In the editor, we’ve coded two values beforehand: li and fb, denoting the number of profile views your LinkedIn and Facebook profile had on the last day of recordings. Go through the instructions to create R code that generates a ‘social media score’, sms, based on the values of li and fb.
INSTRUCTIONS 70 XP Finish the control-flow construct with the following behavior:
If both li and fb are 15 or higher, set sms equal to double the sum of li and fb. If both li and fb are strictly below 10, set sms equal to half the sum of li and fb. In all other cases, set sms equal to li + fb. Finally, print the resulting sms variable to the console. Show Answer (-70 XP) HINT There are several ways to solve this exercise. The easiest will be to use an if-else if-else construct, and maintain the order of the instructions in your construct. You’ll need the & operator in this approach.