Exercises 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Programming and Statistics in R

Exercise 1

This sheet is primarily concerned with vectors and arithmetic.

1. Assign a variable x to be equal to 12. Assign a variable y to be equal


to 5.

> x <- 12
> y <- 5
p
2. Calculate x2 + y 2 . Assign a variable r = x2 + y 2 . What is the value
of r?

3. Delete the variables x, y, r [the rm() function can take multiple argu-
ments].

> rm(x, y, r)

4. Set X = [12, 24, 36, ..., 120], Y = [5, 10, 15, ..., 50] [use seq()].

5. If the following code is run, what is the output?

> R <- X^2 + Y^2


> R <- sqrt(R)
> R

6. Print correct to 20 decimal places.

7. Assign the vector x to be [1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3] [use rep()].

> x <- rep(1:3, each = 2)


> x <- c(x, x)

8. Create the vector [4, 5, 6].


If you forget to retain a value, you can use the .Last.value command

a <- .Last.value

9. Run the following

> a <- -3:10


> a
> log(a)

What happened? How many NaNs are there?

1
Problems
1. Without using R, determine the result of the following computation

> x <- c(2, 4, 6)


> x^2 / 4 - 1 + 2 * x

2. Generate a vector x of 100 points spaced evenly between 2 and 2


(inclusive). Run the following code. What values are stored in y?

> y <- sin(x)

We can plot values in R (much more on this later). Use the letter l
(for line), not the number 1.

> plot(x, y, type = "l")

You might also like