Chapter 10 Challenge 1

Welcome to our first challenge! To complete it, you will use the code block below, and you must:

  1. Use an if() statement to print “meow” if Paws is a “cat”.
  2. Use an if() else statement to print "woof" if you supply an object that is a "dog" and "meow" if it is not. Try it out with Paws and Scruffy.
  3. Use the ifelse() function to display "woof" for animals that are dogs and "meow" for animals that are cats.
Paws <- "cat"
Scruffy <- "dog"
Sassy <- "cat"

animals <- c(Paws, Scruffy, Sassy)

Here is a cheatsheet with logical operators that can help you completing this exercise:

Command Meaning
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
x&y x AND y
x|y x OR y
isTRUE(x) test if x is true
  1. Use an if() statement to print “meow” if Paws is a “cat”.
if (Paws == "cat") {
    print("meow")
}
## [1] "meow"

2. Use an if() else statement to print “woof” if you supply an object that is a “dog” and “meow” if it is not. Try it out with Paws and Scruffy.

x = Paws
# x = Scruffy
if (x == "cat") {
    print("meow")
} else {
    print("woof")
}
## [1] "meow"

3. Use the ifelse() function to display “woof” for animals that are dogs and “meow” for animals that are cats.

animals <- c(Paws, Scruffy, Sassy)

ifelse(animals == "dog", "woof", "meow")
## [1] "meow" "woof" "meow"

or

for (val in 1:3) {
    if (animals[val] == "cat") {
        print("meow")
    } else if (animals[val] == "dog") {
        print("woof")
    } else print("what?")
}
## [1] "meow"
## [1] "woof"
## [1] "meow"