Introduction

Verify that R and RStudio are downloaded following Lecture 1.
Open RStudio.
In the console enter separately each of the following command lines:

1+1
die <- 1:6
die + die

Exercise 1

  1. Choose any number and add 2 to it.
  2. Multiply the result by 3.
  3. Subtract 6 from the answer.
  4. Divide what you get by 3.

Exercise 2

Define the function “magic” that takes a number as an argument and repeat the steps from Exercise 1. Set “10” as the default value.

magic <- function(__){
  y <- __ + 2
  __ <- __*3
  __ <- __
  __ <- __
  __
}

Call the function “magic” with different values passed as arguments.

magic(10)
magic(2)
magic(7)
magic(1053)

Exercise 3

Write a function named “simple_math” that takes two numbers as input and returns both their sum and their product. Include default values for both arguments.

simple_math <- function(x = __, y = __) {
    sum_result <- __
    product_result <- __
    return(list(sum = sum_result, product = product_result))
}

Test your function

result <- simple_math()
print(result)
result <- simple_math(3, 4)
print(result)

Exercise 4

Let x3 be the following vector

x3 <- c(0, 1, 1, 2, 2, 2, 3, 3, 4)

Imagine what a histogram of x3 would look like. Assume that the histogram has a bin width of 1. How many bars will the histogram have? Where will they appear? How high will each be?

When you are done, plot a histogram of x3 with binwidth = 1, and see if you are right.

Exercise 5

Step 1

The ggplot2 package is a powerful tool for creating a wide range of plots and visualizations in R. 1. Install the ggplot2 package using the following command:

install.packages("ggplot2")

Confirm that the package has been installed by checking the output in your console.

Step 2

After installing the package, load it into your R session:

library(ggplot2)

Step 3

Let’s create a scatter plot to visualize the relationship between two sets of numbers.

  1. Create two vectors of numbers:
x_values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y_values <- c(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
  1. Use ggplot2 to create a scatter plot directly from these vectors:
ggplot() +
  geom_point(aes(x = x_values, y = y_values)) +
  labs(title = "Scatter Plot of x vs. y",
       x = "X Values",
       y = "Y Values")

Explanations

The ggplot() function initializes the plotting environment.
geom_point(aes(x = x_values, y = y_values)) creates a scatter plot with points defined by x_values and y_values.
labs() adds labels and a title to your plot.

LS0tCnRpdGxlOiAiU1RTQ0kgMjEy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