Search code examples
rif-statementdplyrpurrrrlang

if-statement in a function using purrr and dplyr (List Column Workflow) in R


I am trying to estimate differences in means for two hospitals, A and B. Every hospital has different "groups" and I have given them group 1 and 2 in the simulated data set. That is I want to test difference in means between hospital A and B within group 1 and group 2 and in addition I have more than one variable (e.g. value1 and value2). So I have to test value1 between hospital A and B within the groups 1 and 2. Even though I specify method=1 in the call at the end I get the third method (the else part). I am using the infer package for the bootstraping (part of tidyverse or tidymodels).

library(tidyverse)
library(lubridate)
library(readxl)
library(infer)
library(stringr)
library(rlang)

set.seed(1)
A <-data.frame(value1=rnorm(n = 1000, mean = 0.8, sd = 0.2), value2= rnorm(n=10 ,mean=1, sd=0.3)) 
A$hosp <- "A"
A$group <- sample(1:2,nrow(A) , replace=T) 

B= data.frame(value1 = rnorm(n=1200, mean =1 , sd = 0.2), value2= rnorm(n=15, mean=1.1, sd=0.4))
B$hosp <- "B"
B$group <- sample(1:2,nrow(B) , replace=T) 

forskel <- bind_rows(A, B) %>% 
  group_by(group) %>% 
  nest()

rm(A, B)

Bellow is my function.

bootloop <- function(dataset, procestid, method, reps = 4, alpha = 0.05) { 
  procestid <- enquo(procestid)

  diff_mean <- dataset %>% 
    mutate(diff_means  = map(data, function(.x){.x %>% 
        group_by(hosp) %>% 
        summarise(mean(!!procestid, na.rm=TRUE)) %>% 
        pull() %>% 
        diff() })) %>%
    select(-data)


  bootstrap <- dataset %>% 
    mutate(distribution =map(data, function(.x){ .x %>% 
        specify(as.formula(paste0(quo_name(procestid), "~ hosp")) ) %>% 
        generate(reps = reps, type = "bootstrap") %>%
        calculate(stat = "diff in means", order = c( "A", "B"))} )) %>% 
    inner_join(diff_mean, by="group")  

  if (method==1) {
    bootstrap2 <- bootstrap %>% mutate(Bias_Corrected_KI=map2(distribution, diff_means, function(.x, .y){ .x %>% 
        summarise( l =quantile(.x$stat,pnorm(2*qnorm(sum(.x$stat >= .y)/reps) + qnorm(alpha/2))),
                   u= quantile(.x$stat,pnorm(2*qnorm(sum(.x$stat >= .y)/reps) + qnorm(1-alpha/2)))    )}))  }
  if (method==2) {
    bootstrap2 <- bootstrap %>% mutate(Percentile_KI = map(distribution, function(.x){.x %>% 
        summarize(l = quantile(stat, alpha/2),
                  u = quantile(stat, 1 - alpha/2))}))  }
  else {
    bootstrap2 <- bootstrap %>% mutate(SD_KI =map2(distribution, diff_means, function(.x,.y){.x %>% 
        get_confidence_interval(level = (1 - alpha), type="se", point_estimate = .y)})) 
  }
return(bootstrap2)

}

procestimes <- list("value1", "value2")


a <- map(syms(procestimes), bootloop , dataset=forskel, method=1 ,  reps=1000)
a

Even though I specify method=1 in the call I get the third form of confidence interval in the else statement.

[[1]]

# A tibble: 2 x 5
  group data                 distribution         diff_means SD_KI           
  <int> <list>               <list>               <list>     <list>          
1     1 <tibble [1,086 x 3]> <tibble [1,000 x 2]> <dbl [1]>  <tibble [1 x 2]>
2     2 <tibble [1,114 x 3]> <tibble [1,000 x 2]> <dbl [1]>  <tibble [1 x 2]>

[[2]]
# A tibble: 2 x 5
  group data                 distribution         diff_means SD_KI           
  <int> <list>               <list>               <list>     <list>          
1     1 <tibble [1,086 x 3]> <tibble [1,000 x 2]> <dbl [1]>  <tibble [1 x 2]>
2     2 <tibble [1,114 x 3]> <tibble [1,000 x 2]> <dbl [1]>  <tibble [1 x 2]>

Solution

  • I suppose you forget to nest the if statements, try this:

    bootloop <- function(dataset, procestid, method, reps = 4, alpha = 0.05) { 
      procestid <- enquo(procestid)
    
      diff_mean <- dataset %>%
        mutate(diff_means  = map(data, function(.x){.x %>%
            group_by(hosp) %>%
            summarise(mean(!!procestid, na.rm=TRUE)) %>%
            pull() %>%
            diff() })) %>%
        select(-data)
    
      bootstrap <- dataset %>%
        mutate(distribution =map(data, function(.x){ .x %>%
            specify(as.formula(paste0(quo_name(procestid), "~ hosp")) ) %>%
            generate(reps = reps, type = "bootstrap") %>%
            calculate(stat = "diff in means", order = c( "A", "B"))} )) %>%
        inner_join(diff_mean, by="group")
    
      if (method==1) {
        bootstrap2 <- bootstrap %>% mutate(Bias_Corrected_KI=map2(distribution, diff_means, function(.x, .y){ .x %>% 
            summarise( l =quantile(.x$stat,pnorm(2*qnorm(sum(.x$stat >= .y)/reps) + qnorm(alpha/2))),
                       u= quantile(.x$stat,pnorm(2*qnorm(sum(.x$stat >= .y)/reps) + qnorm(1-alpha/2)))    )}))  }
      else {  # here you should open a curly brackets with else, and close it of course
      if (method==2) {
        bootstrap2 <- bootstrap %>% mutate(Percentile_KI = map(distribution, function(.x){.x %>% 
            summarize(l = quantile(stat, alpha/2),
                      u = quantile(stat, 1 - alpha/2))})) }
      else {
        bootstrap2 <- bootstrap %>% mutate(SD_KI =map2(distribution, diff_means, function(.x,.y){.x %>% 
            get_confidence_interval(level = (1 - alpha), type="se", point_estimate = .y)})) 
      }}
      return(bootstrap2)
    
    }
    

    With results:

    bootloop (forskel, value1, method=1, reps = 4, alpha = 0.05)
    # A tibble: 2 x 5
      group data                 distribution     diff_means Bias_Corrected_KI
      <int> <list>               <list>           <list>     <list>           
    1     1 <tibble [1,086 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]> 
    2     2 <tibble [1,114 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]> 
    > bootloop (forskel, value1, method=2, reps = 4, alpha = 0.05)
    # A tibble: 2 x 5
      group data                 distribution     diff_means Percentile_KI   
      <int> <list>               <list>           <list>     <list>          
    1     1 <tibble [1,086 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]>
    2     2 <tibble [1,114 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]>
    > bootloop (forskel, value1, method=3, reps = 4, alpha = 0.05)
    # A tibble: 2 x 5
      group data                 distribution     diff_means SD_KI           
      <int> <list>               <list>           <list>     <list>          
    1     1 <tibble [1,086 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]>
    2     2 <tibble [1,114 x 3]> <tibble [4 x 2]> <dbl [1]>  <tibble [1 x 2]>