3

I'm trying to write a relatively simple user-defined function to output cross-tabulations, but not really sure why it is not running.

My testdata:

fp_within = structure(list(weight_cat.w1 = structure(c(1L, 2L, 2L, 1L, 1L, 
2L, 1L, 1L, 3L, 3L, 3L, 3L, NA, 3L, 3L, 2L, NA, NA, NA, NA), .Label = c("1", 
"2", "3"), label = "Weight (Wave 1)", class = c("labelled", "factor"
)), weight_cat.w2 = structure(c(1L, 2L, 2L, 1L, 1L, 2L, 1L, NA, 
2L, 3L, 3L, 2L, 1L, 3L, 3L, 2L, 2L, 2L, 3L, 1L), .Label = c("1", 
"2", "3"), label = "Weight (Wave 2)", class = c("labelled", "factor"
))), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"
))

My code:

library(expss)
library(tidyr)

xtable = function(wave1, wave2, name) {

  xtab = fp_within %>%
  tab_cells(wave1) %>% 
  tab_cols(wave2) %>% 
  tab_stat_cases() %>% # tab_stat_cases = counts
  tab_pivot() %>% 
  set_caption(glue("Table showing agreement in {name} across waves (N)"))

  return(xtab)

}

xtable(weight_cat.w1, weight_cat.w2, "weight")

This throws an error which says...

Error in eval(expr, envir = e, enclos = baseenv()) : 
  object 'weight_cat.w1' not found

This works outside the function and I am expecting a output like:

Table showing agreement in weight across waves (N)                                                                   
 |                 |              | Weight (Wave 2) |      |      |
 |                 |              |               1 |    2 |    3 |
 | --------------- | ------------ | --------------- | ---- | ---- |
 | Weight (Wave 1) |            1 |            1519 |  309 |    5 |
 |                 |            2 |             300 | 1229 |  299 |
 |                 |            3 |               6 |  278 | 1559 |
 |                 | #Total cases |            1825 | 1816 | 1863 |
Dani
  • 161
  • 9

1 Answers1

2

Arguments weight_cat.w1 and weight_cat.w2 are evaluated before it comes to tab_*. Because there are no such variables outside your dataset error is thrown. To avoid preliminary evaluation you need to take a special care about it by using eval(substitute(...)):

xtable = function(wave1, wave2, name) {
    xtab = eval(substitute({
        fp_within %>%
            tab_cells(wave1) %>% 
            tab_cols(wave2) %>% 
            tab_stat_cases() %>% # tab_stat_cases = counts
            tab_pivot()%>% 
            set_caption(glue("Table showing agreement in {name} across waves (N)"))
    })) 

    return(xtab)

}

Gregory Demin
  • 4,596
  • 2
  • 20
  • 20
  • Thank you so much! I've never come across this type of error and was having so much difficulty understanding why. – Dani May 09 '20 at 14:42