Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Loops and Conditionals in R - short

Corey Chivers
March 22, 2013
260

Loops and Conditionals in R - short

Corey Chivers

March 22, 2013
Tweet

Transcript

  1. •R is a full fledged programming language. It can do

    loops and conditionals. i <- runif(1,0,100) if(i <= 50) { print(‘i is pretty small’) } Control Structures for(i in 1:100) { print(i) }
  2. •A loop will be executed over and over. Control Structures

    fruits<- c('apple','orange','banana','pear') for(fruit in fruits) { print(fruit) }
  3. •Combining loops with conditionals can be very powerful. Control Structures

    fruits<- c('apple','orange','banana','pear') for(fruit in fruits) { print(fruit) if(fruit == 'banana') print(paste(fruit,'rama!',sep='') }
  4. Challenge 1) Print out all the numbers between 1 and

    100, but if the number is a multiple of 3, print ‘fizz’ instead. 2) Extend your code so that for multiples of 5, it prints out ‘buzz’. HINT: To get the remainder of integer division, use %%. Ex: 4 9%%5