I have a function that generates dataframes with the following structure:
df <- data.frame(selected.variable = paste(letters[1:5], '_'),
percentage = c(50, 20, 10, 10, 10))
from a much larger dataframe.
That is, in the dataframes I am working with there is one column with the labels for the selected variable and a second column that gives the percentage of cases in which that label occurs.
I want to create tables of these dataframes using the package flextable https://github.com/davidgohel/flextable. I can do this directly using code like the following:
percent_format <- function(x){
sprintf("%.1f %%", x)
}
labels_format <- function(x) {
x <- gsub(pattern = '_', replacement = '', x = x)
return(x)
}
table <- regulartable(df)
table <- set_header_labels(table, selected.variable = 'New name', percentage = 'Percentage')
table <- set_formatter(table, selected.variable = labels_format,
percentage = percent_format)
I would like to write a function that updates the name and format of the selected variable programmatically - something like this:
make.flextable <- function(data, variable, variable.name) {
percent_format <- function(x){
sprintf("%.1f %%", x)
}
labels_format <- function(x) {
x <- gsub(pattern = '_', replacement = ' ', x = x)
return(x)
}
table <- regulartable(data)
table <- set_header_labels(table, variable = variable.name, percentage = 'Percentage')
table <- set_formatter(table, variable = labels_format,
percentage = percent_format)
return(table)
}
However, I cannot work out how to pass the name of the selected variable (e.g., "selected.variable" in example above) to flextable. I have tried to use the map2 function as per this question:
In nested data frame, pass information from one list column to function applied in another
but have not been able to make it work.