This code block below utilizing dplyr::if_else()
works without issue and produces the flextable shown.
library(tidyverse)
library(flextable)
# utilizing dplyr if_else
df1 <- tibble(col1 = c(5, 2), col2 = c(6, 4)) %>%
mutate(col3 = if_else(apply(.[, 1:2], 1, sum) > 10 & .[, 2] > 5,
"True",
"False"))
df1 %>% flextable() %>% theme_zebra()
I first tried this with base R ifelse()
and got the error shown below. The error doesn't seem to make any sense. Can somebody explain? My data frame doesn't have anywhere near 15 columns.
# utilizing base R ifelse
df2 <- tibble(col1 = c(5, 2), col2 = c(6, 4)) %>%
mutate(col3 = ifelse(apply(.[, 1:2], 1, sum) > 10 & .[, 2] > 5,
"True",
"False"))
df2 %>% flextable() %>% theme_zebra()
# Error in rbindlist(x$content$data) :
# Item 5 has 15 columns, inconsistent with item 1 which has 14 columns.
# To fill missing columns use fill=TRUE.
Not a flextable
expert but after breaking down your problem I observe
df <- tibble::tibble(col1 = c(5, 2), col2 = c(6, 4))
ifelse(apply(df[, 1:2], 1, sum) > 10 & df[, 2] > 5, "True", "False")
# col2
#[1,] "True"
#[2,] "False"
which is 2 X 1 matrix and
dplyr::if_else(apply(df[, 1:2], 1, sum) > 10 & df[, 2] > 5, "True", "False")
#[1] "True" "False"
is a character vector. So if you do
df2 <- tibble(col1 = c(5, 2), col2 = c(6, 4)) %>%
mutate(col3 = as.character(ifelse(apply(.[, 1:2], 1, sum) > 10 & .[, 2] > 5,
"True", "False")))
it works as expected.