Well done for getting this far! We’ve covered a lot in this course:
You’re not expected to have comitted all of this to memory already, learning any programming language takes more than three hours. It is only by continuing to use R and practise that you will become confident. These notes will remain online so feel free to refer back to them at any time.
Let’s end this session with a more difficult challenge. We’re going to make a calculator which can read numerical operations from a file and print the answers to the screen.
Start by making a file called
calc.txtwith the following contents:
4 * 6
5 + 6
457 - 75
54 / 3
4 + 6
Make sure that you have the spaces between each number and the operator.
Write a program which reads in that file and performs the mathematical operations listed. It should output something like:
4 * 6 is 24
5 + 6 is 11
457 - 75 is 382
54 / 3 is 18.0
4 + 6 is 10
There are some extra functions that you may need;
strsplit(line, " ")[]will split a line of text into words and will return a list of those words.
cat(line, "is", value, "\n")will print values to the screen, while adding a newline onto the end of each line.
This workshop has given you a beginning introduction on R as a programming language. This, together with our Intermediate R should provide you with a firm foundation as you continue to learn R and apply it for statistical programming and data science applications.
If you’d like to learn more R take a look at this excellent book by Hadley Wickham:
Once you have completed this workshop and Intermediate R, you will be ready to take are future workshops, Introduction to Data Analysis in R and “Applied Data Analysis in R”. These will be linked here once they are ready.
All text is published under a Creative Commons Attribution 4.0 International License with all code snippets licensed as MIT.
The source for the material can be found on GitHub where fixes are welcome.