0

I am fairly new to the R language. I am running a chi-square test for some ordinal data. But, because I have a few variables to run through, I decided to write a small function to wrap around all the other functions I've been calling, so that I could just call the function with the arguments and get the outputs.

But I ran into an issue when I called the function. I got the following message: "Error in eval(predvars, data, env) : object 'WGHT' not found".

Thanks in advance for pointers to solving this issue.

Below is the function I wrote

chi2_test_multicomparisons <- function(data, w, x, y){
  
  # crosstab the data 
  cross_tab = xtabs(w ~
                    x + y,
                    data=data,
                    exclude=c("NS", "Not applicable"))
  
  # perform chi2 test
  chi2_test = chisq.test(cross_tab, correct=TRUE)
  
  # get the proportions for columns
  prop = round(prop.table(cross_tab, 2), 2)
  
  # extract std and adjusted std residuals
  std_residuals = questionr::chisq.residuals(cross_tab)
  adjust_std_residuals = questionr::chisq.residuals(cross_tab, std=TRUE)
  
  # perform pairwise comparisons
  pair_wise = rcompanion::pairwiseNominalIndependence(t(cross_tab),
                                                      fisher = FALSE,
                                                      gtest  = FALSE,
                                                      chisq  = TRUE,
                                                      method = "fdr")
  list(cross_tab,
       chi2_test,
       prop,
       std_residuals,
       adjust_std_residuals,
       pair_wise)
}

# call the function
chi2_test_multicomparisons(data=df2, w=WGHT, x=HSI, y=ISMIN)
GSA
  • 751
  • 8
  • 12
  • You need to take care when passing in symbols to functions that take formulas like `xtabs`. The duplicate uses `lm` but it's the same idea. Since you only seem to use `x` `y` and `z` in the formula, it would be easier just to pass the formula itself in. Something like `chi2_test_multicomparisons(data=df2, WGHT ~ HSI, +ISMIN)` and then you wouldn't have to worry about manipulating lazy expressions – MrFlick Feb 24 '23 at 03:28
  • @MrFlick I made some changes to the script and it worked with some ideas from you. The changes I made: ```chi2_test_multicomparisons <- function(data, termlabels, response){ .formula <- reformulate(termlabels, response) cross_tab = xtabs(.formula, data=data, exclude=c("Not stated", "Not applicable")) # call the function chi2_test_multicomparisons(data=df2, termlabels=c('HSI', 'ISMIN'), response='WGHT')``` – GSA Feb 24 '23 at 04:30

0 Answers0