Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a user-defined function using expss::cro()

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 |
like image 636
Dani Avatar asked Dec 22 '25 02:12

Dani


1 Answers

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)

}

like image 126
Gregory Demin Avatar answered Dec 24 '25 18:12

Gregory Demin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!