-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-chap3.Rmd
59 lines (37 loc) · 6.88 KB
/
03-chap3.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
---
output:
html_document: default
---
# Beginning R Programming {#chap3}
## The Workspace Setup
Obtain R from the [Comprehensive R Archive Network (CRAN)](https://cran.r-project.org/) and install it in the usual way that you install other software. You can use R from the command line in a terminal by typing R (Mac and Linux) or by clicking on the R icon (Windows). However, using R in this way is usually quite tortuous. It is much better to use an Interactive Development Environment (IDE). We shall use RStudio as our IDE. Download and install RStudio from the [Posit](https://posit.co/) web site. Make sure you install the free version. After installation, start it up in the usual way for your system. An important point to note: __RStudio is not R!__. RStudio is merely an interface to R. You should normally not need to cite RStudio in reports etc. Just cite R. To cite R, type ``citation()`` at the R prompt. It will output a citation that you can paste into your reports.
Open RStudio by clicking on the RStudio icon. A window should pop up with three panes. The pane on the left is the R console. This is where R output will appear. You can also type commands right in there. Minimise the R console and you should see another pane: This is the source pane. You can open new R documents there and edit your code. Make sure you save your code with the extension ``.R``. That will allow RStudio to recognise your R file and give you text coloration and other goodies. The two panes on the right hand side of the window include facilities for examining your workspace environment, viewing plots and help files and a number of other things. Now we are ready to start programming!
## First steps
Go to the top-left pane and type.
```{r, eval=FALSE}
cat("Hello World!")
```
Press the ``run`` button at the top right of the pane. You should see the output come out in the Console pane. Congratulations! This is your first R program. A "Hello World" program is traditionally the first program a new programmer writes on a new system that they are learning. You have joined the ranks of computer programmers!
Some comments about your program: The program calls a function called ``cat`` which is a function that prints its arguments in the Console. "cat" stands for "concatenate." You can use ``cat()`` to construct sentences from separate words, as the name suggests. In our case there was only one argument: "Hello World!" so that got printed. "Hello World!" is called a string (short for "character string"). So cat() concatenates strings together. Try:
```{r, eval=FALSE}
cat("I said,", "Hello World!")
```
You can see that the strings are concatenated and are printed out at the Console. I mentioned that ``cat()`` is a function. Functions are the building blocks of computer programs. You will be writing your own functions to do a variety of things. Inside the parentheses, you can put "arguments." which is what the function works on. These are the inputs to the function. The function can have outputs, called "return values" and functions can also have side-effects. For ``cat()``, the side-effect is to print out something at the Console prompt. The ``cat()`` function does not return a value.
Functions have __definitions__. They are what you spend most of the time coding. A typical function definition is:
```{r}
mycat <- function (str) {
cat("This is a", str)
}
```
Notice that we are using the __assignment character__ ``<-`` to give a name to the function ``mycat()``. Then follows the keyword ``function``. The __body__ of the function is enclosed within the curly braces. The function calls the ``cat()`` function and its argument is ``str``. In this case, as ``cat()`` doesn't return a value, neither will our function. Here is a test:
```{r}
result <- mycat("dog")
result
```
Note that the function has a side-effect because ``cat()`` has a side-effect. (Printing the sentence). Note also that ``mycat()`` doesn't return a value (actually the value ``NULL`` which is "nothing" in R.)
## The Art of R Programming
I have learned many languages such as: BASIC, Pascal, Lisp, R, MATLAB, and Julia. I also have some knowledge of FORTRAN and C. Mostly, I am self taught. I have found that the best way to learn a new computer language is to do two things.
- __Get a good tutorial book.__ A good book is your friend. Working through the book will usually teach you everything you need to know, at least at a basic level. You can use the book for reference if you have forgotten how to do things. You can also look up new techniques as you become a better programmer. We use the Art of R Programming because it is a great technical introduction that will give you a good foundation to work from. Using a book, rather than relying on YouTube videos or Google means that you should get a well-rounded introduction to the language, examining all its important aspects evenly. However, should you find Google, YouTube, or even ChatGTP useful, then you should use them. Although the goal is to produce working code, in this course we will be encouraging you to test your __understanding__ of code as well as your ability to write it. We will also be encouraging you to __write well__, so that you can produce code that is readable and easy to maintain.
- __Have a programming project in mind.__ This can be as simple or as complex as you want. Although as a raw beginner, you should probably restrict yourself to very simple problems which demonstrate the various aspects and capabilities of the language. I encourage you to think up a project for yourself. You could work on interesting problems that have been raised in other previous courses, or something completely new and different. For example, a game or some piece of usable code that you will use in the future. It's up to you! We will brainstorm ideas for projects in the workshops. Essentially, we will be having our own mini [hackathon](https://en.wikipedia.org/wiki/Hackathon). Go to [this padlet](https://padletuq.padlet.org/sblomberg11/g20f0qpnnpcuqmou) and post your ideas.
Now to work! Go to "The Art of R Programming" and work through the text up to page 83. This will give you a good grounding in the basics of data types in R: Vectors, matrices, arrays, lists. Work through all the example code: Type it into the top left-hand pane and use the Run button to run your code. While you are reading, consider your own toy problem and how to apply R to it. Experiment along the way! Alternatively, you could work on this problem, which will give you some practice with R as you read through the chapters:
- A letter of the alphabet can be considered "odd" if its position in the alphabet is described by an odd number. If it is described by an even number, the letter is "even." Write an R function that returns the number of odd letters and the number of even letters in a string of arbitrary length. Hint: There is a function called ``strsplit`` that you can use to split up a string into its constituent characters. See ``?strsplit``.