Please, consider the following MWE. I'm practicing a technique where I bind the results from several linear models to a data frame (tibble), then apply custom functions (here, grossly simplified for this MWE) to do some rounding/other modifications, then finally pass the tibble to flextable.
library(dplyr)
library(flextable)
# Load example data
data("mtcars")
# Run linear models
model1 <- lm(mpg ~ hp, data = mtcars)
model2 <- lm(mpg ~ hp + wt, data = mtcars)
# Extract the statistics
coef_table1 <- summary(model1)$coefficients["hp", c("Estimate", "Std. Error", "Pr(>|t|)")]
coef_table2 <- summary(model2)$coefficients["hp", c("Estimate", "Std. Error", "Pr(>|t|)")]
# Combine results to matrix; then, convert to tibble
results <- rbind(coef_table1, coef_table2) %>% as_tibble()
# Name the models
results <- results %>% mutate(Model = c("Model1", "Model2")) %>% relocate(Model, .before = Estimate)
# Display results
results %>% flextable()
# Create custom round function for statistics other that p-values
custom_round <- function(x) {
case_when(
x >= 0 && x < 0.01 ~ "<.01",
TRUE ~ paste0(format(round(x, 2), nsmall = 2))
)
}
# Create custom function for p-values
custom_round_p <- function(x) {
case_when(
x >= 0 && x < 0.05 ~ "<.05",
TRUE ~ paste0(format(round(x, 2), nsmall = 2))
)
}
# Apply the custom round functions to different sections of
# the results tibble with apply()
results_rounded <- bind_cols(results[1],
apply(results[2:3], 2, custom_round),
apply(results[4], 2, custom_round_p))
#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'
#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'
#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'
#> Warning in x >= 0 && x < 0.05: 'length(x) = 2 > 1' in coercion to 'logical(1)'
#> Warning in x >= 0 && x < 0.05: 'length(x) = 2 > 1' in coercion to 'logical(1)'
# Display rounded results
results_rounded %>% flextable()
Created on 2023-04-28 (except the flextable parts) with reprex v2.0.2
The code works fine, but apply()
throws the above warnings. How much are these of relevance in the usage depicted in this MWE?