Moses
Moses

Reputation: 1484

Is there a way to have a similar gtsummary table within a function

I am trying to create a table with gtsummay package inside a function. I find problem with value of N not correct. Am not sure whether am missing something. I would like just to have the value of N after filtering. I have introduced missing values in the grade variable for demonstration purposes.

library(gtsummary)
library(dplyr)
trialmiss <- trial %>% mutate(grade = factor(ifelse(age<10, NA, as.character(grade))))

# My function
mytable <- function(variable){
  trialmiss %>%
    select(variable) %>%
    filter(!is.na(variable)) %>%
    tbl_summary()
}

mytable("grade")

# Desired Output

trialmiss %>%
  filter(!is.na(grade)) %>%
  select(grade) %>% tbl_summary()

Upvotes: 0

Views: 380

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You may use .data pronoun.

mytable <- function(variable){
  trialmiss %>%
    select(variable) %>%
    filter(!is.na(.data[[variable]])) %>%
    tbl_summary()
}

mytable("grade")

enter image description here

You may also use include sym (filter(!is.na(!!sym(variable)))) Or get for the same (filter(!is.na(get(variable)))).

Upvotes: 2

Related Questions