Chapter 10 Challenge 1
Welcome to our first challenge! To complete it, you will use the code block below, and you must:
- Use an
if()
statement to print “meow” ifPaws
is a “cat”. - 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 withPaws
andScruffy
. - Use the
ifelse()
function to display"woof"
foranimals
that are dogs and"meow"
foranimals
that are cats.
<- "cat"
Paws <- "dog"
Scruffy <- "cat"
Sassy
<- c(Paws, Scruffy, Sassy) animals
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 |
- Use an
if()
statement to print “meow” ifPaws
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
.
= Paws
x # 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.
<- c(Paws, Scruffy, Sassy)
animals
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"