Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
rworkshop8 [2014/11/03 15:21] johannabradie [if and if/else statements] |
rworkshop8 [2014/11/03 16:18] (current) johannabradie |
||
|---|---|---|---|
| Line 100: | Line 100: | ||
| **Exercise** | **Exercise** | ||
| - | 1. Create an if statement to display | + | <code rsplus> |
| - | 2. Create a vector of positive and negative values. Use R to take the square root of all positive values in the vector and print "Negative value" where this is not possible. | + | Paws<-"cat" |
| + | Scruffy<-"dog" | ||
| + | Sassy<-cat | ||
| + | animals<-c(Paws,Scruffy,Sassy) | ||
| + | </code> | ||
| + | |||
| + | 1. Use an if statement to print "meow" if Paws is a "cat". | ||
| + | |||
| + | <hidden> | ||
| + | <code rsplus> | ||
| + | if(Paws=="cat") { | ||
| + | print("meow")} | ||
| + | </code> | ||
| + | </hidden> | ||
| + | |||
| + | 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. | ||
| + | |||
| + | |||
| + | <hidden> | ||
| + | <code rsplus> | ||
| + | if(Scruffy=="dog") { | ||
| + | print("woof") | ||
| + | } else { | ||
| + | print ("meow") | ||
| + | } | ||
| + | |||
| + | if(Paws=="dog") { | ||
| + | print("woof") | ||
| + | } else { | ||
| + | print ("meow") | ||
| + | } | ||
| + | </code> | ||
| + | </hidden> | ||
| + | |||
| + | 3. Use an ifelse statement to display "woof" for animals that are dogs and "meow" for animals that are cats. | ||
| + | |||
| + | <hidden> | ||
| + | <code rsplus> | ||
| + | ifelse(animals=="dog","woof","meow") | ||
| + | </code> | ||
| + | </hidden> | ||
| ==== Loops ==== | ==== Loops ==== | ||
