Programming Foundations Part 2
Objectives
We’ll expand on the last module by discussing how to chain together commands to create functions and programs. We will discuss how to develop an algorithm, which is the list of steps required to solve a problem. Writing an algorithm is like writing a recipe for someone who has never cooked before: you have to be very specific about what ingredients to use, and when and how to add them. We’ll learn how to build these algorithms into our own custom functions.
Readings
You should read these chapters before you come to class:
- R for Psychological Science - Functions
- R for Psychological Science - Programming
In-class exercises
We will follow along with the examples given in the textbook. Open the R project called programming-foundations, and save today’s work in a Quarto report called part-2.qmd.
Weekly assignment
First, make sure you have completed all of the exercises in the above chapters. We will have already completed most of them in class. All of the solutions should be included in your Quarto report. Then, solve these additional problems using the concepts you have learned in class. For now, you should avoid using other predefined functions unless noted below.
As always, your Quarto report should be organized with headings and comments explaining your work.
- List all of the prime numbers from 1 to 1000. Start by writing out your plan in comment form, and then fill in the code.
- Create a function
is_prime()that helps you solve this problem.
- Create a function
- Write your own functions to give descriptive statistics for a vector variable storing multiple numbers. Write functions for the following without using R intrinsics: mean, mode, median, range, standard deviation
- It’s ok to use
sum()andlength()in your solutions. - For at least one of these, see if you can come up with two different solutions.
- The output should be a vector with the descriptive statistics, with names included (refer back to the Vectors chapter).
- It’s ok to use
Some of these problems were adapted from this website.