write a function to subset a data.table, then wight unit test for that function in r

Function to Subset a data.table

To subset a data.table, we can use i argument. Using i argument, we can filter rows based on one or multiple conditions. Here's an example function to subset a data.table:

main.r
library(data.table)

subset_dt <- function(dt, col, val) {
  dt[col == val]
}
78 chars
6 lines

This function expects three arguments:

  • dt: the data.table to be subsetted.
  • col: the column name to filter on.
  • val: the value to filter on.

The function returns a subset of dt where values in col column match with val.

Unit Test for the Function

We can write a unit test to check if the function is working as expected. To write the unit test, we need to use the testthat package. Here's an example unit test:

main.r
library(testthat)

# Sample data
dt <- data.table(x = c("a", "b", "c"), y = 1:3)

# Unit test for subset_dt function
test_that("subset_dt function returns expected output", {
  expect_equal(subset_dt(dt, "x", "a"), data.table(x = "a", y = 1))
  expect_equal(subset_dt(dt, "y", 3), data.table(x = "c", y = 3))
})
312 chars
11 lines

This unit test checks if the function returns expected output for two scenarios:

  • subset_dt(dt, "x", "a"): it should return a data.table with one row where column x has value "a" and column y has value 1.
  • subset_dt(dt, "y", 3): it should return a data.table with one row where column x has value "c" and column y has value 3.

If the unit test runs without any errors, it means the function is working as expected.

gistlibby LogSnag