R Programming
  • The wikipedia of R by me
  • Hello R
    • -What is R & RStudio
    • -Learning sources
    • -R online editor
    • -R environment
  • Data types
    • -Dealing with Number
    • -Dealing with String
    • -Dealing with Dates
    • -Dealing with NA's
    • -Dealing with Logicals
    • -Dealing with Factors
  • R data
    • -R object
    • -Data structures
      • --Basics
      • --Managing Vectors
      • --Managing Matrices
      • --Managing Data Frames
    • -Functions
    • -Importing/exporting data
    • -Shape&Transform data
    • -R management
  • Visualizations
  • Intro to R Bootcamp
    • -01-introduction
    • -02-data preparation
    • -03-data transformation
    • -04-visualization
  • R programming track
    • -a-Introduction to R
      • --1-Intro to basics
      • --2-Vectors
      • --3-Matrices
      • --4-Factors
      • --5-Data frames
      • --6-Lists
    • -b-Intermediate R
      • --1-Conditionals and Control Flow
      • --2-Loops
      • --3-Functions
      • --4-The apply family
      • --5-Utilities
    • -d-Writing Functions in R
      • --1-A quick refresher
      • --2-When and how you should write a function
      • --3-Functional programming
      • --4-Advanced inputs and outputs
      • --5-Robust functions
  • Data Wrangling with R
  • R-tutor
    • #R introduction
    • #Elementary Statistics with R
  • Hands-On Programming with R
  • R for Data Science
  • Advanced R
  • ggplot2
  • R packages
  • Statistik-1
  • Statistik-2
  • Statistik-3
  • Zeitreihen & Prognosen
  • Descriptive Analytics
  • Predictive Analytics
  • Prescriptive Analytics
  • R Graphics Cookbook
    • ggplot2 intro
    • ggplot2 custome
    • ggplot top-50
  • #Exploratory Data Analysis
    • -Data Summary
    • -Checklist Solution
  • #Data Mining
    • Untitled
    • Untitled
  • #Machine Learning
    • Intro to ML
    • Intro alghorithms
    • 1. Supervised Learning
  • Master R for Data Science
    • Learning R
    • Untitled
    • Untitled
  • Data Science Projects
    • Simple linear regression:
Powered by GitBook
On this page
  • #1-While loop
  • #2-Write a while loop
  • #3-Throw in more conditionals
  • #4-Stop the while loop: break
  • #5-Build a while loop from scratch
  • #6-For loop
  • #7-Loop over a vector
  • #8-Loop over a list
  • #9-Loop over a matrix
  • #10-Mix it up with control flow
  • #11-Next, you break it
  • #12-Build a for loop from scratch
  1. R programming track
  2. -b-Intermediate R

--2-Loops

Previous--1-Conditionals and Control FlowNext--3-Functions

Last updated 6 years ago

#1-While loop

​​

#100 "Cevi ist Cevi"
cevi=1

while(cevi<=100){
  
  print(paste("cevi ist",cevi))
  cevi=cevi+1
}

#2-Write a while loop

#Code a while loop with the following characteristics:
#The condition of the while loop should check if 
#speed is higher than 30.
#Inside the body of the while loop, print out "Slow down!".
#Inside the body of the while loop, decrease the speed 
#by 7 units.
#This step is crucial; otherwise your while loop will 
#never stop.

# Initialize the speed variable
speed <- 64
# Code the while loop
while ( speed>30) {
  
  print("Slow down!")
  speed<-speed-7
}
# Print out the speed variable
speed

#3-Throw in more conditionals

#If the speed is greater than 48, have R print out 
#"Slow down big time!", 
#and decrease the speed by 11.
#Otherwise, have R simply print out "Slow down!", 
#and decrease the speed by 6.

# Initialize the speed variable
speed <- 64

# Extend/adapt the while loop
while (speed > 30) {
  print(paste("Your speed is",speed))
  if ( speed>48) {
    print("Slow down big time!")
    speed=speed-11
    
  } else {
    print("Slow down!") 
    speed=speed-6
  }
}

#4-Stop the while loop: break

#Adapt the while loop such that it is abandoned 
#when the speed of the vehicle 
#is greater than 80. 
#This time, the speed variable has been 
#initialized to 88; keep it that way.

# Initialize the speed variable
speed <- 88

while (speed > 30) {
  print(paste("Your speed is", speed))
  
  # Break the while loop when speed exceeds 80
  if ( speed>80) {
    break
  }
  
  if (speed > 48) {
    print("Slow down big time!")
    speed <- speed - 11
  } else {
    print("Slow down!")
    speed <- speed - 6
  }
}

#5-Build a while loop from scratch

#Finish the while loop so that it:
#prints out the triple of i, so 3 * i, at each run.
#is abandoned with a break if the triple of i 
#is divisible by 8,
#but still prints out this triple before breaking.

# Initialize i as 1 
i <- 1

# Code the while loop
while (i <= 10) {
  print(3*i)
  if ((3*i)%%8==0) {
    break
  }
  i <- i + 1
}

#6-For loop

#7-Loop over a vector

#Write a for loop that iterates over all the 
#elements of linkedin 
#and prints out every element separately. 
#Do this in two ways: using the loop 
#version 1 and the loop version 2 
#in the example code above.

# The linkedin vector has already been defined for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)

# Loop version 1
for(cevi in linkedin){
  print(cevi)
}
# Loop version 2
for(cevi in 1:length(linkedin)){
  print(linkedin[cevi])
}

#8-Loop over a list

#As in the previous exercise, loop over the nyc 
#list in two different ways 
#to print its elements:
#Loop directly over the nyc list (loop version 1).
#Define a looping index and do subsetting 
#using double brackets (loop version 2).

# The nyc list is already specified
nyc <- list(pop = 8405837, 
            boroughs = c("Manhattan", "Bronx", 
            "Brooklyn", "Queens", "Staten Island")
            , 
            capital = FALSE)

# Loop version 1
for (cevi in nyc){
  print(cevi)
}
# Loop version 2
for (cevi in 1:length(nyc)){
  
  print(nyc[[cevi]])  
}

#9-Loop over a matrix

#Finish the nested for loops to go over the elements in ttt:
#The outer loop should loop over the rows, with 
#loop index i (use 1:nrow(ttt)).
#The inner loop should loop over the columns, 
#with loop index j (use 1:ncol(ttt)).
#Inside the inner loop, make use of print() 
#and paste() to print out information 
#in the following format: "On row i and column j 
#the board contains x", 
#where x is the value on that position.

# The tic-tac-toe matrix ttt has already 
#been defined for you

vector<-c("O",  NA  , "X" ,NA,   "O",  "O" ,"X",  NA,"X")

ttt<-matrix(vector,nrow=3,ncol =3)
ttt

# define the double for loop
for (i in 1:nrow(ttt)) {
  for (j in 1:ncol(ttt)) {
    print(paste("On row", i , "and column", j, 
    "the board contains", ttt[i,j]))
  }
}

#10-Mix it up with control flow

#Add code to the for loop that loops over 
#the elements of the linkedin vector:
#If the vector element's value exceeds 10, 
#print out "You're popular!".
#If the vector element's value does not exceed 10, 
#print out "Be more visible!"

# The linkedin vector has already been defined for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)

# Code the for loop with conditionals
for (li in linkedin) {
  if (li>10 ) {
    print("You're popular!")
  } else {
    print("Be more visible!")
  }
  print(li)
}

#11-Next, you break it

#Extend the for loop with two new, separate 
#if tests in the editor as follows:
#If the vector element's value exceeds 16, 
#print out "This is ridiculous,
#I'm outta here!" and have R abandon the for loop (break).
#If the value is lower than 5, 
#print out "This is too embarrassing!" 
#and fast-forward to the next iteration (next).

# The linkedin vector has already been defined for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)

# Extend the for loop
for (li in linkedin) {
  if (li > 10) {
    print("You're popular!")
  } else {
    print("Be more visible!")
  }
  
  # Add if statement with break
  if(li>16){
    print("This is ridiculous, I'm outta here!")
    break
    
  }
  
  # Add if statement with next
  if(li<5){
    
    print("This is too embarrassing!")
    next
  }
  
  print(li)
}

#12-Build a for loop from scratch

#Initialize the variable rcount, as 0.
#Finish the for loop:
#if char equals "r", increase the value of rcount by 1.
#if char equals "u", leave the for loop 
#entirely with a break.
#Finally, print out the variable rcount to the 
#console to see if your code is correct.

# Pre-defined variables
rquote <- "r's internals are irrefutably intriguing"
chars <- strsplit(rquote, split = "")[[1]]

# Initialize rcount
rcount <- 0

# Finish the for loop
for (char in chars) {
  if(char=="r"){
    rcount<-rcount+1
  }
  
  if(char=="u"){
    
    break
  }    
}

# Print out rcount
print(rcount)

​ ​

While loop video
For loop video