functions exercises

February 7, 2016
By

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

functions exercisesToday we’re practising functions! In the exercises below, you’re asked to write short R scripts that define functions aimed at specific tasks. The exercises start at an easy level, and gradually move towards slightly more complex functions.

Answers to the exercises are available here.

If you obtained a different solution than the one posted on the answers page, please let us know of your solution by posting it as a comment at the end of that page.

Exercise 1
Create a function that will return the sum of 2 integers.

Exercise 2
Create a function what will return TRUE if a given integer is inside a vector.

Exercise 3
Create a function that given a data frame will print by screen the name of the column and the class of data it contains (e.g. Variable1 is Numeric).

Exercise 4
Create the function unique, which given a vector will return a new vector with the elements of the first vector with duplicated elements removed.

Exercise 5
Create a function that given a vector and an integer will return how many times the integer appears inside the vector.

Exercise 6
Create a function that given a vector will print by screen the mean and the standard deviation, it will optionally also print the median.

Exercise 7
Create a function that given an integer will calculate how many divisors it has (other than 1 and itself). Make the divisors appear by screen.

Exercise 8
Create a function that given a data frame, and a number or character will return the data frame with the character or number changed to NA.

Image by Ninjahatori (Own work) via Wikimedia Commons

To leave a comment for the author, please follow the link and comment on their blog: R-exercises.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)