473,545 Members | 2,025 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lesson 5 (part1) – r programming structures

nbiswas
149 New Member
The programming structures that we will examine include: control flow statements and user defined functions.
In previous lessons we were either performing summary or descriptive statistics across single variables, but in this lesson we will examine the interrelationsh ips between variables. Interrelationsh ip analysis comes in different forms and in this lesson we will examine covariance, correlation, and linear regression techniques.
You have probably discovered that as we write more complex R scripts there are scenarios that require decision making and R provides many flexible options to control the flow of execution using conditional and iteration expressions.
We also mentioned that R is a functional and an object-oriented programming language. In this lesson we will examine how we define and use functions during our analysis.
We will learn how to create different types of R functions.
We have learned how to examine data trends over a single variable using a histogram or over 2 variables using scatterplots. In the final part of this lesson we will learn how to analyze the relationship between 2 variables through learning about covariance, correlation, and linear regression.
Let's examine decision making in R.
In this example we generate 1 random number between 1 and 100 using the runif() or random uniform distribution function. This function returns a floating point value and in this scenario we would like to simply deal with integer values so we use as.integer() function to discard the decimal portion of our number.
To enable reproducible results we have decided in line 2 to set a static seed value to R's pseudo-random number generator prior to the request for a number.
If you would like randomness when this script is executed you would obviously use a different seed value each time.
The purpose of the script is to print a statement that the random number is either odd or even.
We state the conditional expression inside parenthesis following the if statement. Here we are checking if the result of applying the modulus 2 operator to the number is zero (0) or not. If there is no remainder then we know that the number is indeed even and R will execute the code defined within the curly {} brackets.
If the first conditional expression is evaluated FALSE then the next conditional expression will be tested or in this case the final else clause will be executed.
Note the location of the brackets and indentation shown in this example. This example is consistent with various R coding style guidelines.
Throughout this lesson we will be using simulated data.
R has many methods of creating data that can be used for analysis. Two of the most common types of distributions are uniform distributions and normalized distributions.
The functions runif and rnorm can be used to generate a vector of values with the corresponding distribution properties.
With normal distributions you provide a mean and a standard deviation. For example, if you wanted to create a large data set of 100 possible test scores with a normal distribution around a mean mark of 75 and a standard deviation or measure of distribution of 2 you could use the example as shown. To visualize and verify your data distribution you could use the plot or hist functions.
As with most functional programming languages R provides program structures to control iteration or looping behaviour. We will examine each of these iteration operations in this lesson.
The repeat statement can be used to define a block of statements that will continue to iterate indefinitely.
The break statement is used to exit the loop. In this example we simply check that the value stored in the variable x is greater than 9 we exit the loop otherwise we will print out the current value of x, increment the value by one and the loop repeats. When the value stored in the variable x is greater than 9 we use the break statement to leave the loop and continue in the script.
A conditional looping structure defines the initial or precondition within parenthesis.
In this scenario our entry condition to the looping code involves checking if the value stored in the variable curr is less than or equal to the number of marks in our integer vector called marks.
Recall that in R code blocks are usually defined using the curly or brace brackets {}. It is possible to avoid using brace brackets if the expression is a single line and another option is to combine multiple expressions on a single line using the semi-colon (:). In this example we are actually doing both of these techniques. This may seem confusing so style guidelines should be considered if you have multiple developers working on a single project.
On line 3, we initialized the value of the variables p and curr on a single line.
On line 6, we use an if statement to check if a value in the marks vector is greater than or equal to 50, if it is then we increment the value in the p variable by one.
On line 7 the if statement above is considered a complete expression and therefore the code on line 7 will execute for each iteration.
Once the looping condition is no longer true the msg will be generated using the sprintf() function and then sent to the standard output display using the cat() function.
When the iteration scenario has a well-defined number of iterations, a for statement can be used in R.
The first example uses a sequence function to create a temporary vector of values. The value of i will begin with a value of 5 and then the value will be incremented by 5 until it reaches 15 for the final iteration.
The second example iterates over an existing vector of integers and since the index value of the marks vector is not required we can use a simplified version of the for statement. As we iterate through the values, the counter p will be incremented when the value in 50 or more. This style of for loop can be used to iterate over any vector data structure and it will always examine each element of the vector from the first position to the final position.
Sep 4 '14 #1
1 5036
zmbd
5,501 Recognized Expert Moderator Expert
nbiswas:
Please provide proper citations for these articles.
-z
Sep 29 '14 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

15
3037
by: christopher diggins | last post by:
I have written an article on how to do Aspect Oriented Programming in vanilla C++ (i.e. without language extensions or other tools such as AspectC++). The article is available at http://www.heron-language.com/aspect-cpp.html. I would appreciate some feedback on the article, and also I would like to know whether I am repeating some prior work....
65
4208
by: Roger Smythe | last post by:
A means for the progressive decomposition a problem space into increasingly simpler component parts such that these component parts represent higher levels of conceptual abstraction, and are completely independent of each other except for their well-defined interfaces. This was an attempt to explain the gist of OOP to programmers accustomed...
25
4306
by: Justin Robbs | last post by:
I am trying to write the communcations part of a Point of Sale program for the Convenience Store industry. The setup in each store will have varying numbers of registers. There could be as few as 2 or as many as 12. The program I am working on runs on a computer which communicates to our gas pumps and sends status changes to all registers....
15
2201
by: UrsusMaximus | last post by:
While preparing a Python411 podcast about classes and OOP, my mind wondered far afield. I found myself constructing an extended metaphor or analogy between the way programs are organized and certain philosophical ideas. So, going where my better angels dare not, here is the forbidden fruit of my noodling: Spiritual Programming: It seems...
3
2033
by: Juan R. | last post by:
In http://canonicalscience.blogspot.com/2006/04/scientific-language-canonml-is.html] I presented some generic requirements for a markup language for science and mathematics. Basic features of CanonML and ampliations and improvements over TeX, SGML, XML or Scheme based encodings are listed below. However, let me an incise first. Rememeber...
1
1371
by: Tina888 | last post by:
I am a very new programmer. Trying to solve this problem. Create a static function called Part1 with the following signature: public static void Part1() Call this function from the file's Main function. In Part1 write some code that writes the following pattern to the console: * ++
151
7943
by: istillshine | last post by:
There are many languages around: C++, JAVA, PASCAL, and so on. I tried to learn C++ and JAVA, but ended up criticizing them. Is it because C was my first programming language? I like C because, comparatively, it is small, efficient, and able to handle large and complex tasks. I could not understand why people are using and talking about...
1
5342
nbiswas
by: nbiswas | last post by:
In this lesson we will initially learn about the features and uses of R. R is a software environment that is excellent for data analysis and graphics. It was initially created in 1993 by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand. They created R as a language to help teach introductory statistics to their...
1
4620
nbiswas
by: nbiswas | last post by:
Welcome to the lesson on R data structures. To perform any meaningful data analysis we need to collect our data into R data structures. In this lesson we will explore the most frequently used data types and data structures. R can be used to analyze many different forms of data. We will explore the built-in data types of R. Data analysis...
1
5199
nbiswas
by: nbiswas | last post by:
In this lesson we will learn how to import external data from files into R. We will also learn how to export, or write, the data to files if needed. Once we have our data loaded into memory we can perform data filtering or querying to focus on key aspects of our data set. We will also learn how to reorder our data within data frames and...
0
7411
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7926
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7439
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5987
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4962
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.