PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 8, 2022

[FIXED] How to convert formula equation for functions in R (wilcox test) etc?

 October 08, 2022     r, statistics     No comments   

Issue

I'm trying to make a function to accept different formula groups for the wilcox test. I do not understand how to change the formula equation to make it modular.

Example below:

library(rstatix)
library(dplyr)
data("ToothGrowth")
df <- ToothGrowth

df %>%
      group_by(dose) %>%
      wilcox_test(data =., len ~ supp) %>%
      adjust_pvalue(method = "bonferroni") %>%
      add_significance("p.adj")


# This Does Not Work

wilcox_test2 <- function(df,x,y){
return(df %>%
  group_by(dose) %>%
  wilcox_test(data =., x ~ y) %>%
  adjust_pvalue(method = "bonferroni") %>%
  add_significance("p.adj"))

}

wilcox_test2(df,df$len,df$supp)

Solution

We could pass the column names as argument and create the formula wihtin the function using reformulate

library(dplyr)
library(rstatix)
wilcox_test2 <- function(df, x, y){

 df %>%
   group_by(dose) %>%
   wilcox_test(data =., reformulate(y, response = x) ) %>%
   adjust_pvalue(method = "bonferroni") %>%
   add_significance("p.adj")

}

-testing

> wilcox_test2(df, "len", "supp")
# A tibble: 3 × 10
   dose .y.   group1 group2    n1    n2 statistic       p  p.adj p.adj.signif
* <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl>   <dbl>  <dbl> <chr>       
1   0.5 len   OJ     VC        10    10      80.5 0.0232  0.0696 ns          
2   1   len   OJ     VC        10    10      88.5 0.00403 0.0121 *           
3   2   len   OJ     VC        10    10      49.5 1       1      ns          


Answered By - akrun
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing