Search code examples
rdatatablecalculated-columnssurveyflextable

How to put standard error below estimate in a table in R, and transfer to flextable


I am creating a summary statistics table using the apistrat data with the output as a table in R (hoping to eventually format with flextable). I am hoping to manipulate the table so the standard error of each variable appears directly below the mean/median value I've collected. Here's an example:

dstrata <- apistrat %>%
  as_survey_design(strata = stype, weights = pw) 

dstrata <- dstrata %>%
  mutate(api_diff = api00 - api99) 

dstrata %>%
  summarise(api_diff = survey_mean(api_diff, vartype="se" )) 

api_diff api_diff_se
     <dbl>       <dbl>
1     32.9        2.08 

#so as you can see now, the standard error appears as its own column. Is there a way to reformat the table so it appears like this? 

   api_diff 
     <dbl>       
1     32.9 
     (2.08) 
 

Once it's in this form, how can I transpose it to appear as a flextable? Whenever I try to do so I receive the following error:

> table=flextable(dstrata)
Error in flextable(dstrata) : is.data.frame(data) is not TRUE 

Thank you!


Solution

  • Something liike that:

    library(flextable)
    library(srvyr)
    library(survey)
    library(dplyr)
    data(api)
    
    # stratified sample
    dstrata <- apistrat %>%
      as_survey_design(strata = stype, weights = pw)
    
    dstrata <- dstrata %>%
      mutate(api_diff = api00 - api99) 
    
    dat <- dstrata %>%
      summarise(api_diff = survey_mean(api_diff, vartype="se" )) 
    
    flextable(dat, col_keys = "api_diff") %>% 
      compose(j = 1, value = as_paragraph(api_diff, " (", api_diff_se, ")")) %>% 
      autofit()
    

    enter image description here