Best practices while writing R code Exercises

In the exercises below we cover some of the best practices while writing a small piece of R code or a full automated script. These are some of the practices which should be kept in mind while coding, trust me it will make your life a lot easier.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Exercise 1
We want to create a numeric vector. The values of this vector should be between 1 and 10, starting from 1 with a difference of 2. Below is the code to generate a numeric vector.Make the suitable changes so that it follows standard practice for assignments.
NumVector = seq(1,10,by=2)

Exercise 2
The command below installs “car” package. Make changes in the command below so that all the packages get installed on which “car” is dependent.
install.packages("car")

Exercise 3
Make the changes in the below code so that it is easy for other users to read and it follows the standard practice while writing an if/else statement in R.
y
x

if (y == 0)
{
log(x)
} else {
y ^ x
}

Exercise 4
Update the below code so that it is easy for other users to read it.
NumVector

Exercise 6
Update the below code such that it first checks if the “dplyr” package is present. if it is already present, don’t install it just load the package.If the package is not present, install it and then load it.

install.packages("dplyr",dependencies = T)

Exercise 7
Change the below code so that the it doesn’t print package related information while loading the plyr package.

library(plyr)

Exercise 8
Make the changes in the below code so that it doesn’t print warnings while calculating the correlation value between two vectors.
a
b
cor(a,b)

Exercise 9
Update the below command so that it calls the ‘rename’ function from ‘plyr’ package. The same function is present in both the packages- ‘plyr’ and ‘rename’.

rename(head(mtcars), c(mpg = "NewName"))

Exercise 10
Create a scalar vector ‘a’ with a value of 10e-02 (1/100). Below code prints the same vector in scientific format. Make changes to print in a numeric format.
a
print(a)