`dplyr::if_else()` 与基础 R `ifelse()` 相比 - 为什么 rbindlist 错误?

`dplyr::if_else()` compared to base R `ifelse()` - why rbindlist error?

下面使用 dplyr::if_else() 的代码块可以正常工作并生成所示的 flextable。

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()

我首先尝试使用 base R ifelse() 并得到如下所示的错误。该错误似乎没有任何意义。有人可以解释吗?我的数据框没有接近 15 列。

# 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.

不是 flextable 专家,但在分解你的问题后我观察到

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"

这是 2 X 1 矩阵并且

dplyr::if_else(apply(df[, 1:2], 1, sum) > 10 & df[, 2] > 5, "True", "False")
#[1] "True"  "False"

是一个字符向量。所以如果你这样做

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")))

它按预期工作。

如@ronak-shah 所示,您的 ifelse 正在创建一个矩阵,这并不令人满意 flextable ;)

使用 flextable 之前不需要格式化数据。例如,我会在那里使用 colformat_lgl

df2 <- tibble(col1 = c(5, 2), col2 = c(6, 4)) %>% 
  mutate( col3 = rowSums(.) > 10 & col2 > 5 )

flextable(df2) %>% 
  colformat_lgl("col3", true = "True", false = "False")