## R Exercises for Beginners 1-10 – Solutions

**1.**

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

length(lynx) order(lynx) which(lynx < 500) subset(lynx, lynx < 500)

**2.**

- Get a Histogram of the lynx dataset
- Adjust the bin size to have 7 bins
- Remove the labs, change to 2 alternating colors
- 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.**

- Extract Sepal.Length from the iris dataset and call it mysepal
- Get the square root, summation, max and min of mysepal
- 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.**

- Install and load library “dplyr”
- Call help for function arrange of “dplyr”
- Deinstall “dplyr”

install.packages("dplyr") library(dplyr) ?arrange remove.packages("dplyr")

**5.**

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

- Repeat x 4 times, but there should be a 1 at the end and beginning
- 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.**

- Get a subset of mtcars with transmission type: manual, and call it mysubset
- Extract the first 2 variables of the first 2 observations

mysubset = subset(mtcars, am == 1) mysubset[c(1,2), c(1,2)]

**7.**

- Get the first 9 observations of “mtcars”
- 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.**

- Get the means of the first 2 columns in the “iris” dataset by Species
- Create vector x which is the alternation of 1 and 2, 75 times, check the length
- Attach x to iris as dataframe “irisx”
- 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) irisx = data.frame(iris, x); head(irisx) by(irisx[,c(1,3,4)], irisx$x, colSums)

**9.**

- How many observations in “lynx” are smaller than 500?
- How many observations in “iris” have a Sepal.Length greater or equal 5?

sum(lynx < 500) sum(iris$Sepal.Length >= 5)

**10.**

- Plot a simple xy plot with “iris” Sepal.Length vs. Sepal.Width
- Enlarge the scale limits: y from 0 – 5, x from 3 – 9
- 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)

Pingback: R Tutorials | R Exercises for Beginners - 1-10 | R Tutorials

good one for the beginners…i enjoyed!!

these are good exercises to learn the necessary syntax