Blog posts on Data Science, Machine Learning, Data Mining, Artificial Intelligence, Spark Machine Learning

Saturday, February 27, 2016

Control Structures Loops in R

As part of Data Science tutorial Series in my previous post I posted on basic data types in R. I have kept the tutorial very simple so that beginners of R programming  may takeoff immediately.
Please find the online R editor at the end of the post so that you can execute the code on the page itself.
In this section we learn about control structures loops used in R. Control strcutures in R contains conditionals, loop statements like any other programming languages.



Loops are very important and forms backbone to any programming languages.Before we get into the control structures in R, just type as below in Rstudio:
 ?control 

If else statement:
#See the code syntax below for if else statement 
if(x>1){
 print("x is greater than 1")
 }else{
  print("x is less than 1")
  } 

#See the code below for nested if else statement

 x=10
  x=10
 if(x>1 & x<7){
     print("x is between 1 and 7")}else if(x>8 & x< 15){
         print("x is between 8 and 15")
     }

[1] "x is between 8 and 15" 

For loops:
As we know for loops are used for iterating items
 #Below code shows for  loop implementation
x = c(1,2,3,4,5)
 for(i in 1:5){
     print(x[i])
 }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

While loop :

 #Below code shows while loop in R
x = 2.987
while(x <= 4.987) { 
     x = x + 0.987
     print(c(x,x-2,x-1)) 
 }
[1] 3.974 1.974 2.974
[1] 4.961 2.961 3.961
[1] 5.948 3.948 4.948

Repeat Loop:
The repeat loop is an infinite loop and used in association with a break statement.

 #Below code shows repeat loop:
a = 1
 repeat { print(a) a = a+1 if(a > 4) break }
[1] 1
[1] 2
[1] 3
[1] 4

Break statement:
A break statement is used in a loop to stop the iterations and flow the control outside of the loop.

 #Below code shows break statement:
x = 1:10 
 for (i in x){ 
     if (i == 2){ 
         break 
     }
     print(i)
 }
[1] 1

Next statement:
Next statement enables to skip the current iteration of a loop without terminating it.

 #Below code shows next statement 
x = 1: 4 
 for (i in x) { 
     if (i == 2){ 
         next}
     print(i)
 }
[1] 1
[1] 3
[1] 4

Creating a function in R:
function() is a built-in R function whose job is to create functions. In the below example function() takes one parameter x, executes a for loop logic.
The function object thus created using function() is assigned to a variable ('words.names'). Now this created function will be called using the variable 'word.names'

 #Below code shows us, how a function is created in R:

Syntax: 
function_name = function(parameters,..){ code}
 
words = c("R", "datascience", "machinelearning","algorithms","AI") 
words.names = function(x) {
     for(name in x){ 
         print(name) 
     }
} 
#Calling the function
 words.names(words)
[1] "R"
[1] "datascience"
[1] "machinelearning"
[1] "algorithms"
[1] "AI"

Hands on exercise of what we have learnt so far


We create a data frame DF, run for loop, ifelse in a function and call the function
#create 3 vectors name,age,salary
name = c("David","John","Mathew")
age = c(30,40,50)
salary = c(30000,120000,55000)
#create a data frame DF by combining the 3 vectors using cbind() function
DF = data.frame(cbind(name,age,salary))
#display DF
DF
    name age salary
1  David  30  30000
2   John  40 120000
3 Mathew  50  55000
#dimensions of DF
 dim(DF)
[1] 3 3
 
#write a function which displays the salaried person name
findHighSalary = function(df){
     Maxsal = 0
     empname = ""
     for(i in 1:nrow(DF)){
         tmpsal = as.numeric(DF[i,3] )
         if(tmpsal > Maxsal){
             Maxsal = tmpsal
             empname = DF[i,1]
         }
     }
     return(as.character(empname))
 }
#calling the function
findHighSalary(DF)
[1] "Mathew"

59 comments:

  1. Hello there, just became aware of your blog through Google, and found that it is really informative. I am gonna watch out for brussels. I will be grateful if you continue this {in future}. Many people will be benefited from your writing. Cheers! Social media

    ReplyDelete
  2. I used to be very happy to seek out this internet-site.I wanted to thanks on your time for this excellent read!! I definitely having fun with each little bit of it and I've you bookmarked to check out new stuff you weblog post. concrete cylinder

    ReplyDelete
  3. Wow! This blog looks just like my old one! It's on a totally different subject but it has pretty much the same page layout and design. Excellent choice of colors! I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I'm looking to create my own blog and would like to know where u got this from. thanks teeth whitening singapore price

    ReplyDelete
  4. Incredible site, Stack give you warm with a not all that terrible way. I am here on this http://www.ukraineoutsourcingrates.com/net-development-ukraine-rates/ site on the grounds that to consider the smokestack blames and influences my home stack to denounce free. Your data is so cool.

    ReplyDelete
  5. I do agree with all of the ideas you've presented in your post. They're really convincing and will certainly work. Still, the posts are very short for starters. Could you please extend them a bit from next time? Thanks for the post. digital advertising Singapore

    ReplyDelete
  6. Hey There. I discovered your blog the use of msn. This is a really neatly written article. I will be sure to bookmark it and return to learn extra of your useful info. Thanks for the post. I will definitely comeback. digital marketing

    ReplyDelete
  7. Definitely consider that which you stated. Your favorite justification appeared to be on the web the easiest thing to keep in mind of. I say to you, I definitely get irked at the same time as other people think about concerns that they plainly do not recognize about. You managed to hit the nail upon the highest as smartly as outlined out the whole thing with no need side-effects , other folks could take a signal. Will likely be again to get more. Thanks infographics in Singapore website

    ReplyDelete
  8. Hey, I think your website might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, great blog!email marketing singapore

    ReplyDelete
  9. Hi just wanted to give you a quick heads up and let you know a few of the pictures aren't loading properly. I'm not sure why but I think its a linking issue. I've tried it in two different browsers and both show the same outcome. website design services Singapore

    ReplyDelete
  10. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I'm looking to construct my own blog and would like to find out where u got this from. thank you customised jewellery singapore

    ReplyDelete
  11. This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool! corporate gift singapore

    ReplyDelete
  12. Hi there this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience. Any help would be enormously appreciated! accounting service in Singapore

    ReplyDelete
  13. Wonderful blog! Do you have any hints for aspiring writers? I'm hoping to start my own website soon but I'm a little lost on everything. Would you suggest starting with a free platform like Wordpress or go for a paid option? There are so many options out there that I'm totally confused .. Any suggestions? Many thanks! sem seo

    ReplyDelete
  14. I’m not certain where you are getting your info, but good topic. I must spend some time studying much more or working out more. Thank you for excellent info I used to be searching for this info for my mission. nose filler singapore

    ReplyDelete
  15. Hello, I think your website might be having browser compatibility issues. When I look at your blog site in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, terrific blog!social media in Singapore

    ReplyDelete
  16. Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!smok mag baby

    ReplyDelete
  17. I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I'm looking to design my own blog and would like to find out where u got this from. cheers
    best bed bug exterminator nyc

    ReplyDelete
  18. Hello would you mind sharing which blog platform you're working with? I'm looking to start my own blog soon but I'm having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I'm looking for something completely unique. best thing for cellulite on thighs

    ReplyDelete
  19. Hi there, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you reduce it, any plugin or anything you can advise? I get so much lately it's driving me insane so any support is very much appreciated. top web design companies

    ReplyDelete
  20. I was wondering if you ever considered changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?
    seo in singapore

    ReplyDelete
  21. That requires a process to determine whether there is smoke and whether your right to fresh air trumps my right to blow smoke wherever I want. To determine what rights we each have, we create government.

    media marketing in Singapore

    ReplyDelete
  22. My pal Verruca used to be within the equal line she lives in Acne, She observed a brand new marketplace by way of handing out loose samples external the STD hospital.

    marketing firm

    ReplyDelete
  23. Simply want to say your article is as amazing. The clarity in your post is just nice and i can assume you are an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work.
    Facebook

    ReplyDelete
  24. Part of the problem of making an accurate voltmeter is that of calibration to check its accuracy.

    marketing courses

    ReplyDelete
  25. Wonderful goods from you, man. I have understand your stuff previous to and you're just extremely magnificent. I really like what you've acquired here, certainly like what you are stating and the way in which you say it. You make it entertaining and you still care for to keep it smart. I cant wait to read far more from you. This is actually a great website. Creating a professional and user-friendly website design

    ReplyDelete
  26. Greetings from Colorado! I'm bored to death at work so I decided to browse your site on my iphone during lunch break. I really like the info you present here and can't wait to take a look when I get home. I'm shocked at how quick your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .. Anyhow, great blog!how to choose a web design company      

    ReplyDelete
  27. Thanks for the post, can I set it up so I receive an update sent in an email whenever you make a new post? seo marketing singapore

    ReplyDelete
  28. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?
    Good math tuition centre

    ReplyDelete
  29. An enormous heap of a commitment of gratefulness is all together for the amount of your determined effort on this site. Betty truly worships doing web appraisal and it is clear why. My accomplice and I get ability with about the dynamic medium you present exceptional proposition on your web blog and too welcome reaction from others on the article while my girl is truly being told to such an extent. Attempt the remainder of the year. You are doing a truly extraordinary work.

    kitchen renovation Singapore

    ReplyDelete
  30. A very informative article with information that will be helpful for a lot of people.
    Buy custom logo design

    ReplyDelete
  31. Valuable information. Thanks for publishing such great information about Grapecity Pool Campus Drive. I have information for you, We can help resolve all the issues befalling AOL email. If you are using AOL email service not being able to perform AOL sign in properly, then you should check our website for detailed information. AOL mail sign in now

    ReplyDelete
  32. Buy the beautiful logo 50% Off, impressive service,
    I expect You'll be satisfied with us. Custom Logo

    ReplyDelete
  33. We understand our clients, and we know that they need only elite Cheap Price Call Girls in Chanakyapuri.
    If you have desires and fantasises that never came true, then you are in for a treat. Hiring an Real Call Girls Photo in Faridabad will give you the chance to enjoy a lot.
    Our super hot Real Call Girls Photo in Faridabad are meant for providing best pleasures.
    Just call us on the given numbers and we bet that you are going to enjoy with Model Call Girls in Agra.
    There are lots of Model Call Girls in Agra available for you. We have lots of variety to offer too.
    You can get Model Call Girls in Ajmer, Bengali, Bihari, Punjabi, Latin, Russian, and lots more. Variety is key to us because clients prefer changes in their life.

    ReplyDelete
  34. Learning programming for software development is now easy because of blog like this

    ReplyDelete
  35. Terrific post however I was wondering if you could write a litte more on this subject? I'd be very thankful if you could elaborate a little bit more. Bless you! coal lawyer

    ReplyDelete
  36. Thank you for the useful information which you shared throughout your blog. I appreciate the way you shared the relevant, precious, and perfect information. Furthermore, I would like to share some information about Peergrowth. Peergrowth is one of the best executive search firms in UAE, to know more about the services, just visit the website and take complete information about Peergrowth. I hope, you will get immediate assistance and the right information through the website.

    ReplyDelete
  37. Greetings from Idaho! I'm bored to tears at work so I decided to browse your site on my iphone during lunch break. I love the information you present here and can't wait to take a look when I get home. I'm shocked at how quick your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .. Anyways, good site! custom made wardrobe singapore

    ReplyDelete
  38. Amazing and helpful article.
    Thanks for sharing it with us.

    law dissertation Writing Service

    ReplyDelete
  39. To register your Arlo account. First, open any web browser on your pc or phone (you can also use an app on mobile). Enter your Netgear Arlo Login details into the Web portal. After that, you can do the setup you want, like a camera or doorbell. Losing the login details can be an enormous problem for Arlo users. So that’s, why we are here. In this kind of issue, we fill fetch you details for you to Sresolve your issue


    ReplyDelete
  40. We offer necessary help to Google Wifi users with their setups. Many users face minor issues while setting up Google Wifi. Despite the fact, that Google Wifi setups are one of the most user-friendly devices. If you have any difficulties too with your setup, check out our website. Along with setup, you could also learn about login and important configurations. So, get in touch with us.

    ReplyDelete
  41. Update the Firmware updates are released automatically to all connected Arlo devices.Automatic updates happen between 3:00 a.m. and 5:00 a.m. to minimize cameradowntime. If the firmware update is a major one, you might be unable to streamfrom your camera until your firmware is updated.You can wait until the update happens automatically between 3:00 a.m. and 5:00a.m., or you can update your firmware manually.Note:Even when you cannot view your camera live, motion and sound detection still workand your camera still records based on the currently selected mode.¾ To update your Arlo Baby firmware manually:1. Tap the Arlo iconYou can also enterThe Devices page displays.2. Tap or click Settings > My Devices.The My Devices page displays.3. Select the Arlo Baby camera that you want to update.4. Tap or click Device Info > Firmware > Update.WARNING: Do not disconnect your camera while the firmware update is in progress.5. Wait for the firmware update to complete.The camera's LED blinks amber and blue while the firmware is downloading andinstalling. After the firmware is installed, the camera reboots and the LED is off.When the LED lights again and the pattern stops changing, your camera is availableto stream.Settingson your mobile device.arlo.netgear.com
    Arlo Pro Netgear Firmware Update

    ReplyDelete
  42. We provide help to Bellsouth users. You have an issue with the Bellsouth.Net Email Login, and then come to us. For the correct procedure to log in, you can visit our website. There you can check for all the information related to login. But anyhow, you are unable to log in, and then kindly contact us.

    ReplyDelete
  43. Learn how to use spectrum email with us. You can also access your Brighthouse Email through the spectrum email login page. Enter your email and password, and your good to go, but visit our website if you need any further help. You can also contact our expert.

    ReplyDelete
  44. Download the MangaHub stream app for fun comics. Read the characters that are amazing, suspicious, and thrilling. Then, have a fun time with the favorite genre of your type. Choose from action, adult, comedy, drama, and many more. Characters in these comics potray Japanese culture in an enjoyable way. Moreover, there will be no disturbing ads at your showtime.

    ReplyDelete
  45. When it comes to troubleshooting offline camera issues, there are numerous aspects to consider. For instance, the internet connection may be unstable, the batteries may be dead, or the camera may be located far away from the Arlo base station. You can help yourself by going through some simple and easy-to-follow troubleshooting steps. When you contact the Arlo customer support team, the specialists will advise you to take the following actions.

    ReplyDelete
  46. Hey thanks for its blog that is informative and educative. Kubota Tractor

    ReplyDelete
  47. It is amazing and wonderful to visit your site. Thanks for sharing this information, this is useful to me.
    Click here if you are looking for long handle umbrellas

    ReplyDelete
  48. Nice and amazing content this is share a unique information with us. Force Tractor

    ReplyDelete