# Scripting Loops exercises Vol.2

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

Answers to the exercises are available here.

Exercise 1

Using the following variables:
``` x=1 i=c(1:10) ```
For this exercise, write a for() loop that increments x by two for each i.

Exercise 2
Using the following variables:
``` x=1 y=40 i=c(1:10) ```
For this exercise, write a for() loop that increments x by three and decrease y by two, for each i.

Exercise 3
Using the following variables:
``` a,b ```
For this exercise, write a nested for() loop (where the outer for loop increment a from 2 to 8 by 1, and the
inner for loop increment b from 1 to 6 by 1) that print “a, ‘ less than ‘,b” if a

Exercise 4
Using the following variable:
``` x=c(2,4) ```
For this exercise, type a while () loop that adds even numbers to x, while the length of x is less than 12.
For example, in the first iteration you get `x = 2,4,6`, and the third `x =2,4,6,8`.

Exercise 5

Using the following variable:
``` a=15:10 b=20:15 ```
For this exercise, type a while () loop that computes a vector` x=225 224 221 216 209 200` ,such that

``` x[1]=a[1]*b[6] x[2]=a[2]*b[5] x[3]=a[3]*b[5] . . x[6]=a[6]*b[1]```

``` ```

Exercise 6

Using the following variable:
``` a=1:10 ```
For this exercise, type a while () loop that computes a vector` x=1 3 6 10 15 21 28 36 45 55` ,such that
``` x[1]=a[1] x[2]=a[1]+a[2] x[3]=a[1]+a[2]+a[3] . . ```

Exercise 7

Using the following variable:
``` i=10 x=10 ```
For this exercise, type a repeat () loop that decreasing i computes `x=x/i` until `i=0`.

Exercise 8

Using the following variable:
``` x=100 y=50 i=1 ```
For this exercise, type a repeat () loop that incrementing i computes `x=x-i and y=y+i` until `x.`

``` Exercise 9 Using the following variable: x=as.Date("10/11/2017","%d/%m/%Y") For this exercise, type a repeat () loop that increment x until x is equal to 31/12/2017. Exercise 10 Using the following variable: x=cbind(c(1,2,3,4,9,7,4,3),c(3,1,2,5,3,6,5,3)) For this exercise, type a for() loop that calculate y=3 8 18 44 126 140 100 84, such that y[1]=x[1,1]*x[1,2] y[2]=x[2,1]*sum(x[1:2,2]) y[3]=x[3,1]*sum(x[1:3,2]) . . . y[8]=x[8,1]*sum(x[1:8,2]) Want to practice loops a bit more? We have more exercise sets on this topic here. var vglnk = { key: '949efb41171ac6ec1bf7f206d57e90b8' }; (function(d, t) { var s = d.createElement(t); s.type = 'text/javascript'; s.async = true; s.src = '//cdn.viglink.com/api/vglnk.js'; var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r); }(document, 'script')); Related ShareTweet To leave a comment for the author, please follow the link and comment on their blog: R-exercises. R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more... If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook... ```
``` ```
``` Comments are closed. ```
``` Search R-bloggers (function() { var cx = '005359090438081006639:paz69t-s8ua'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); Recent popular posts Creating Slopegraphs with R A primer in using Java from R - part 1 A guide to working with character data in R future.apply - Parallelize Any Base R Apply Function Using DataCamp's Autograder to Teach R Most visited articles of the week How to write the first for loop in R Installing R packages Using apply, sapply, lapply in R R – Sorting a data frame by the contents of a column How to perform a Logistic Regression in R How to Make a Histogram with Basic R Tutorials for learning R How to Make a Histogram with ggplot2 In-depth introduction to machine learning in 15 hours of expert videos Sponsors // https://support.cloudflare.com/hc/en-us/articles/200169436-How-can-I-have-Rocket-Loader-ignore-my-script-s-in-Automatic-Mode- // this must be placed higher. Otherwise it doesn't work. // data-cfasync="false" is for making sure cloudflares' rocketcache doesn't interfeare with this // in this case it only works because it was used at the original script in the text widget function createCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } function readTextFile(file) { // Helps people browse between pages without the need to keep downloading the same // ads txt page everytime. This way, it allows them to use their browser's cache. var random_number = readCookie("ad_random_number_cookie"); if(random_number == null) { var random_number = Math.floor(Math.random()*100*(new Date().getTime()/10000000000)); createCookie("ad_random_number_cookie",random_number,1) } file += '?t='+random_number; var rawFile = new XMLHttpRequest(); rawFile.onreadystatechange = function () { if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { // var allText = rawFile.responseText; // document.write(allText); document.write(rawFile.responseText); } } } rawFile.open("GET", file, false); rawFile.send(null); } // readTextFile('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt'); readTextFile("https://www.r-bloggers.com/wp-content/uploads/text-widget_anti-cache.txt"); Jobs for R usersR Developerpostdoc in psychiatry: machine learning in human genomicsLead Quantitative DeveloperResearch Data Analyst @ Arlington, Virginia, U.S.Market Research Analyst: Mobility for RSGData Scientist @ New Delhi, IndiaData Scientist/Programmer @ Milwaukee, Wisconsin, U.S. Full list of contributing R-bloggers ```
``` R-bloggers was founded by Tal Galili, with gratitude to the R community. Is powered by WordPress using a bavotasan.com design. Copyright © 2018 R-bloggers. All Rights Reserved. Terms and Conditions for this website var snp_f = []; var snp_hostname = new RegExp(location.host); var snp_http = new RegExp("^(http|https)://", "i"); var snp_cookie_prefix = ''; var snp_separate_cookies = false; var snp_ajax_url = 'https://www.r-bloggers.com/wp-admin/admin-ajax.php'; var snp_ajax_nonce = '82a0c1dc82'; var snp_ignore_cookies = false; var snp_enable_analytics_events = false; var snp_enable_mobile = false; var snp_use_in_all = false; var snp_excluded_urls = []; snp_excluded_urls.push(''); Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.) Click here to close (This popup will not appear again) .snp-pop-109583 .snp-theme6 { max-width: 700px;} .snp-pop-109583 .snp-theme6 h1 {font-size: 17px;} .snp-pop-109583 .snp-theme6 { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field ::-webkit-input-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field :-moz-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field :-ms-input-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field input { border: 1px solid #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field { color: #000000;} .snp-pop-109583 .snp-theme6 { background: #f2f2f2;} jQuery(document).ready(function() { }); var CaptchaCallback = function() { jQuery('.g-recaptcha').each(function(index, el) { grecaptcha.render(el, { 'sitekey' : '' }); }); }; (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "https://www.r-bloggers.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css?ver=3.0.9b"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") ); var themecssurl = "https://www.r-bloggers.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shThemeDefault.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } //document.getElementById("syntaxhighlighteranchor").appendChild(themecss); document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); _stq = window._stq || []; _stq.push([ 'view', {v:'ext',j:'1:6.2.1',blog:'11524731',post:'144129',tz:'-6',srv:'www.r-bloggers.com'} ]); _stq.push([ 'clickTrackerInit', '11524731', '144129' ]); /* <![CDATA[ */ jQuery(function(){ jQuery("ul.sf-menu").supersubs({ minWidth: 12, maxWidth: 27, extraWidth: 1 }).superfish({ delay: 100, speed: 250 }); }); /* ]]> */ ```