UCI COSMOS 2026 Noah Benjamin (adapted material from Sara Tyo and Mine Dogucu)
Slides
Slides can be found on the website (https://cosmos-datascience.netlify.app).
First things first:
Do you have a computer?
Do you have R on your computer?
Do you have RStudio on your computer?
Let’s talk about RStudio
Why is it a nice environment for R coding??
It is an IDE(Integrated Development Environment) that we use to write, manage, and execute R code.
It is open-source and free!! (and works well too)
It’s not the only R-capable IDE, most of the popular ones have R extensions (like VSCode)
Today’s lab
We’re going to get some practice with the basics of R.
The slides will walk through the concepts and serve as a reference. At the same time, we will each be writing the code on our computers to get some hands-on practice. I’ll also be doing it!!
Please stop and ask questions!! It doesn’t have to just be if you’re stuck.
Creating a project in R studio
Create a new project
Creating a project in R studio
Choose a new Quarto project
Creating a project in R studio
Create your new project!!
First, create a Quarto document
This is like a notebook file where you can write both text and code. It’s saved as a .qmd file.
Quarto can run both R and Python!!! We will only be focusing on R.
We can access specific elements in these vectors through indexing
We index through the elements of a vector using the brackets []
So, if we want to access the first element of the fruits vector we write:
fruits[1]
[1] "Apple"
R is a 1-indexed language, meaning that when we index through a list we start at 1
If you are familiar with Python, that is a 0-indexed language
data.frame
One of the most common ways we will store data is in a data frame
It’s like a spreadsheet, that stores data in a grid format
In this grid each column (or row) is its own vector
We can use our vectors about fruit to create a data.frame that stores all the info about fruit
fruit_data <-data.frame(fruit = fruits, color = colors, seeds = seeds)fruit_data
fruit color seeds
1 Apple red TRUE
2 Banana yellow FALSE
3 Orange orange TRUE
data.frame
We can index the data.frame grid with brackets as well, indexing through the rows and columns
fruit_data[row, column]
fruit_data[2, 1] # this will give us the second row, first column entry of fruit_data
[1] "Banana"
We can leave one of the row or column entries blank if we want the entire row or column
fruit_data[,1] # will give us the entire first column
[1] "Apple" "Banana" "Orange"
fruit_data[3,] # will give us the entire third row
fruit color seeds
3 Orange orange TRUE
Functions
Let’s say we have a list of numbers, and we want to find the average of them
numbers <-c(-1, 15, 100, 111, 110)
We could do this this mathematically, by adding up the values and dividing by how many there are
(-1+15+100+111+110)/5
[1] 67
Functions
R has a lot of handy ways of making this quicker for us, however
The sum() function will take the sum of the elements of the vector we pass into it
The length() function will tell us how many elements are in the vector we give it
total <-sum(numbers)how_many <-length(numbers)
total/how_many # so now we can find the mean this way
[1] 67
Functions
Conveniently, R has a mean() function, which will do all of these things for us
mean(numbers)
[1] 67
Functions
Generally, we call functions in the following way:
do(something)
do() is a function; something is the argument of the function.
Functions
Functions are not limited to only one argument:
do(something, colorful)
do() is a function; something is the first argument of the function; colorful is the second argument of the function.
Some arguments might be optional, and start with default values
Functions
To learn about what a function does, we can use a question mark before the function:
?mean
This will tell us what arguments a function expects, and default values for optional ones
Functions
Many functions exist either in base R or in packages that save us from having to write our own code
If you are looking for something specific, Google is your friend!!
More on this coming up soon
Conditional statements
if(condition){ Do Something} else { Do Something Else}
We can add more conditions that are checked sequentially
Conditional statements
if(condition1){ Do something} elseif (condition2) { Do a different thing} else { Do this different thing}
Only one of the blocks will be run depending on which condition is met
Writing a condition
== to check if something is equal (x == 2)
!= to check if it’s not equal to
Traditional inequalities also work: - <, >, <=, >=
Writing a condition
We can also combine multiple conditions, to only execute if both conditions are met, or if one of two is met
&& check for both conditions to be true
ex: if(x == 4 && y < 2), only returns TRUE if both conditions are met
|| checks for at least one of the conditions to be true
ex: if(x == 4 || y < 2), returns TRUE if either of the two conditions are met
Conditional example 1
Minimum height for rollercoaster
height <-63if(height >=63){ # here we check if height is large enough to take the rideprint("Fantastic! Enjoy the rollercoaster")} else {print("OOPS! Sorry, you'll have to wait until next year")}
[1] "Fantastic! Enjoy the rollercoaster"
Conditional example 2
Whether to lend money, using logic in the condition
money <-10greed <-1if(money-1000<0|| greed >50){ # here we check if we don't have enough money, or we are too greedy to lendprint("Sorry I don't have enough money to loan you")}else{print("Sure, here's 1000$.")}
[1] "Sorry I don't have enough money to loan you"
Try and play around with the amount assigned to ‘money’ and ‘greed’.
Make your own
Now, Try and make your own if statement!
if(){print("")}else{print("")}
while loops and for loops
while loops and for loops, as the names suggest repeat (or ‘loop’) a segment of code over and over
a while loop runs code while a certain condition is met
a for loop runs code for a pre-specified number of iterations
while loop syntax
while(condition) { Do this over and over }
Be careful because its easy to write a while loop that runs for ever (and that is bad)
while loop example
x <-0while(x <10) { x <- x +1}
We can put any code we’d like in the loop
while loop example
x <-0while(x <10) { x <- x +1if(x %%2==0) { # check if x is evenprint(x) }}
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
while loop example
We can also forcibly break out of a loop when a certain condition is met, even if the loop has no actual end
x <-1while(TRUE) {if (x ==5) {break }print(x) x <- x +1}
[1] 1
[1] 2
[1] 3
[1] 4
for loop
remember that for loops repeat for a specified number of iterations
in the while loop example we just saw, we manually increased x by 1 every iteration of the loop
for loops are special because they do this automatically
for loop syntax
for(element in vector){ Do this as many times as there are elements in vector}
how this looks in practice:
for loop example
numbers <-c(1, 2, 3, 4, 5)for(num in numbers) {print(num)}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
one of the nice things about this is that the loop will iterate over any list, not just numbers
for loop example
for(fruit in fruits){ # using the fruits vector we defined earlierprint(fruit)}
[1] "Apple"
[1] "Banana"
[1] "Orange"
Creating Functions
Remember the length(), sum(), and mean() functions we saw earlier?
What if we want to make our own functions in R?
Writing your own functions is useful when you find you are rewriting the same code over and over again.
We learned that functions take in arguments that are the user-inputted values when they call the function/
The other indispensable ingredient in a function is a return() statement
When a function hits return(some_value), it immediately ends and outputs the return value
Function syntax
Functions are made using the following syntax, where it’s important to prespecify the input arguments, and how you want them processed.
Comments
As you have already seen, we can write comments in our code chunks.
We use the # symbol
They are just for our reference and do not do anything when we run the chunk
Like writing little notes in the code