Below are the solutions to these exercises on unit testing in R.

#################### # # # Exercise 1 # # # #################### install.packages("testthat") library(testthat) # loading the package #################### # # # Exercise 2 # # # #################### #Passes expect_that(5*2, equals(10)) #################### # # # Exercise 3 # # # #################### #Passes expect_that(5*2, equals(10+ 1e-7)) #fails expect_that(5*2, equals(10+ 1e-6)) #################### # # # Exercise 4 # # # #################### expect_that(2*2, is_identical_to(4+ 1e-8)) #################### # # # Exercise 5 # # # #################### m <- function(x,y){return(x*y)} expect_that(m("2","3"), throws_error("non-numeric argument to binary operator")) #################### # # # Exercise 6 # # # #################### test_that("Testing multiplication function",{ expect_that(m(2,3), equals(6)) expect_that(m(2,c(2,3)), equals(c(4,6))) expect_that(m(2,"3"), throws_error("non-numeric argument to binary operator")) }) #################### # # # Exercise 7 # # # #################### is_greater_10 <- function() { function(x){ expect(x > 10, "Not greater than 10") } } #################### # # # Exercise 8 # # # #################### expect_that(9, is_greater_10()) #################### # # # Exercise 9 # # # #################### test_file(<Path to the file with test script>) #################### # # # Exercise 10 # # # #################### test_dir(<Path to the directory with test files>)

**What's next:**

- Explore all our (>1000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

## Leave a Reply