5.2 Interlude – Examining and debugging a function

If you are unsure how any part of myfun_cat() works, you can investigate the pieces. The method shown here works for understanding a function and also for debugging a function that you are trying to write but which is not working.

The steps are:

  • Assign values to each of the function arguments,
  • run the code inside the function step-by-step and look at the intermediate results,
  • edit as needed, and
  • clean up at the end by removing the function argument values and any objects created in the function code.

For example (results not shown):

# Investigating how the function myfun_cat() works.

# Create the variable x (corresponding to the function argument)
x <- mydat$income

# Now you can run the code in the function and look to see what is happening at
# each step

# Count the number of missing values
nmiss <- sum(is.na(x))
nmiss

# Frequency
n     <- table(x)
n

# Proportion
p     <- prop.table(n)
p

# Putting it together
OUT   <- cbind(n, p)
OUT

# Add nmiss, but first pad to have the right number of rows
nmiss <- c(nmiss, rep(NA, nrow(OUT)-1))
nmiss

# NOTE: To combine nmiss with the matrix OUT we need
# another column with 3 rows. But nmiss only has 1 value
# so we use c() to combine nmiss with 2 NA values.
# Since OUT could have any number of rows, we use rep().
# rep(NA, 2) would produce a vector of 2 NA values.
# In general, we want rep(NA, nrow(OUT)-1)

OUT   <- cbind(OUT, nmiss)
OUT

# Clean up
rm(x, nmiss, n, p, OUT)