## R Exercises for Beginners 1-10 – Solutions

### 1.

1. Get the length of the lynx dataset
2. Create a vector of ordered index numbers (hint: order, increasing)
3. Get 2 vectors (index positions and absolute values) with all observations smaller than 500 (hint: which, subset)
```length(lynx)
order(lynx)
which(lynx &lt; 500)
subset(lynx, lynx &lt; 500)
```

### 2.

1. Get a Histogram of the lynx dataset
2. Adjust the bin size to have 7 bins
3. Remove the labs, change to 2 alternating colors
4. Add a subtitle and a 2 line title
```hist(lynx, col=c("salmon2", "darkblue"), breaks=7,
sub="r-tutorials.com", xlab="", ylab="",
main="Exercise Question\nHistogram")
```

### 3.

1. Extract Sepal.Length from the iris dataset and call it mysepal
2. Get the square root, summation, max and min of mysepal
3. Get the summary of mysepal and compare the results with 3b
```mysepal = iris\$Sepal.Length
sum(mysepal); mean(mysepal); median(mysepal); min(mysepal); max(mysepal)
summary(mysepal)
```

### 4.

1. Install and load library “dplyr”
2. Call help for function arrange of “dplyr”
3. Deinstall “dplyr”
```install.packages("dplyr")
library(dplyr)
?arrange
remove.packages("dplyr")
```

### 5.

`x = c(3,6,9)`

1. Repeat x 4 times, but there should be a 1 at the end and beginning
2. Call the vector of 5a myvec and extract the 5th value (hint: dplyr, nth)
```myvec = c(1, rep(x, times=4), 1)
library(dplyr)
nth(myvec, 5)
```

### 6.

1. Get a subset of mtcars with transmission type: manual, and call it mysubset
2. Extract the first 2 variables of the first 2 observations
```mysubset = subset(mtcars, am == 1)
mysubset[c(1,2), c(1,2)]
```

### 7.

1. Get the first 9 observations of “mtcars”
2. Get the mtcars dataset ordered according to the increasing amount of “carb” (hint for 7b: library dplyr, arrange)
```head(mtcars, 9)
library(dplyr)
arrange(mtcars, carb)
```

### 8.

1. Get the means of the first 2 columns in the “iris” dataset by Species
2. Create vector x which is the alternation of 1 and 2, 75 times, check the length
3. Attach x to iris as dataframe “irisx”
4. Get the sums of the columns of columns 1,3,4 in the “irisx” dataset by the new x
```by(iris[,1:2], iris\$Species, colMeans)
x = rep(1:2, times=75); length(x)
by(irisx[,c(1,3,4)], irisx\$x, colSums)
```

### 9.

1. How many observations in “lynx” are smaller than 500?
2. How many observations in “iris” have a Sepal.Length greater or equal 5?
```sum(lynx &lt; 500)
sum(iris\$Sepal.Length &gt;= 5)
```

### 10.

1. Plot a simple xy plot with “iris” Sepal.Length vs. Sepal.Width
2. Enlarge the scale limits: y from 0 – 5, x from 3 – 9
3. Add a text of your choosing, in red, at the lower part of the plot
```attach(iris)
plot(Sepal.Length, Sepal.Width)
plot(Sepal.Length, Sepal.Width, ylim=c(0,5), xlim=c(3,9))
text(6,1, "r-tutorials.com", col="red", cex=2, lwd=2)
```