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.r78 chars6 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.
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.r312 chars11 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