I am trying to make a function that will return a gt
table of the results of the common psych::describe()
and psych::describeBy()
functions.
the problem is that describeBy()
expects the group argument to be of the form data$vector
rather than just group = vector
.
So
describeBy(data, data$group)
# works
describeBy(data, group)
# doesn't work
this is fine for general use--just a thing to remember. But to use it in a shiny app, I really need it to take the form of the second call in the above.
description<-function(data, group = NULL, fast = TRUE, ...) {
grp<-paste0(deparse(substitute(group)))
#print(grp)
if(is.null(group)) {
data %>%
psych::describe(fast = fast, ...) %>%
tibble::rownames_to_column() %>%
dplyr::select(-c(vars)) %>%
dplyr::mutate(dplyr::across(is.numeric, round, 2)) %>%
gt::gt() %>%
gt::tab_options(
column_labels.font.size = "small",
table.font.size = "small",
row_group.font.size = "small",
data_row.padding = px(3)
) %>%
tab_header(
title = paste0("Data Description")
)
} else {
data %>%
psych::describeBy(group = group, fast = fast, mat= TRUE, ...) %>%
tibble::rownames_to_column() %>%
select(-c(item, vars)) %>%
dplyr::mutate(dplyr::across(is.numeric, round, 2)) %>%
arrange(group1) %>%
group_by(group1) %>%
gt() %>%
gt::tab_options(
column_labels.font.size = "small",
table.font.size = "small",
row_group.font.size = "small",
data_row.padding = px(3))
} %>%
tab_header(
title = paste0("Data Description") ,
subtitle = paste0("Grouped by: ", grp )
)
}
I've tried a lot of variations on enquo, names(), !!, etc. in the group =
call, but I can't quite get it to work right. Can anyone help?
psych::describeBy
does not contain a data argument. Hence you cannot use group
directly from the data. If you need to use that, you would better use the formula option. eg:
psych::describeBy(iris~Species)
if at all you are writing a function, then do:
my_describe <- function(data, group = NULL, fast = TRUE){
if(deparse(substitute(group)) == 'NULL')
psych::describe(data)
else psych::describeBy(as.formula(substitute(data~group)))
}
Note: Note the best way to go about it but it works