在函数中使用flextable函数(例如merge_at,hline)

izkcnapc  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(119)

我试图用程序的方式来设计我的flextables,但是在使用某些函数时遇到了问题,例如merge_at()hline();它们只对我引用的列的最后一个条目进行样式化,而不管我尝试使用哪一行。
这里有一个最小的例子。iris_a变成了我想要的样子,而iris_b以一种我无法理解的方式改变了。

# setup
library(tidyverse)
library(officer)
library(flextable)
thin_border <- fp_border(color = "gray")

setosa <- iris %>% group_split(Species) %>% .[[1]] %>% slice(1:2)
versicolor <- iris %>% group_split(Species) %>% .[[2]] %>% slice(1:2)

iris_a <- bind_rows(setosa, versicolor) %>% mutate(spec = case_when(
    Species == "setosa" ~ "set",
    Species == "versicolor" ~ "versi"
)) %>% flextable()
iris_b <- iris_a

specs <- c("setosa", "versicolor")

# actual transformation

for (k in specs) {
    iris_a<- iris_a%>% hline(., i = ~ Species == k, j = 1:5, border = thin_border)
}
for(k in specs){
    iris_a <- iris_a %>% merge_at(., i = ~ Species == k, j = ~spec)
}
iris_a %>% fix_border_issues()

# success, a nice table; now I wrap the loops into functions

merge_cells <- function(flex, location){
    for(k in location){
    flex <- flex %>% merge_at(., i = ~ Species == k, j = ~spec)    
    }
flex
}

add_vlines <- function(flex, location){
    for (k in location) {
        flex <- flex %>% hline(., i = ~ Species == k, j = 1:5, border = thin_border)
    }
flex
}

iris_b <- iris_b %>%
    add_vlines(., "set") %>%
    merge_cells(., "set")
iris_b %>% fix_border_issues()

不管location设置了什么,结果都是一样的(例如location = specs)。
我也试过用mk_par()来解决这个问题,但没有用。
我哪里做错了?
补遗:忘了补充,location可以设置为 * 任何 *,结果仍然是一样的(iris_b %>% merge_cells(., "something"))。

xoefb8l8

xoefb8l81#

我认为这将帮助你解决你的问题。你的配方才是问题所在。我把这个例子简化成一个更简单的例子。

library(flextable)

dat <- structure(list(Sepal.Length = c(5.1, 4.9, 7, 6.4), Sepal.Width = c(3.5, 
3, 3.2, 3.2), Petal.Length = c(1.4, 1.4, 4.7, 4.5), Petal.Width = c(0.2, 
0.2, 1.4, 1.5), Species = structure(c(1L, 1L, 2L, 2L), levels = c("setosa", 
"versicolor", "virginica"), class = "factor"), spec = c("set", 
"set", "versi", "versi")), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

merge_cells <- function(flex, location){
  for(k in location){
    form <- as.formula(paste0("~ spec %in% '", k, "'"))
    flex <- merge_at(flex, i = form, j = ~spec) 
  }
  flex
}

flextable(dat) |> merge_cells(location = "set")

相关问题