【问题标题】:How to bold/keep measure names in r after merging on common columns合并公共列后如何在 r 中加粗/保留度量名称
【发布时间】:2022-07-25 00:52:37
【问题描述】:

如果我有两个数据框:

tibble1 <- tibble(\"DoB\" = c(\"Year\", \"Month\"),
                  \"Bob\" = c(\"2001\", \"3\"),
                  \"Kevin\" = c(\"1999\", \"9\"), 
                  \"Stewart\" = c(\"1868\", \"11\"))
tibble2 <- tibble(\"Education\" = c(\"School\", \"Degree\"),
                  \"Bob\" = c(\"UNIV\", \"BA\"),
                  \"Kevin\" = c(\"CC\", \"AD\"), 
                  \"Stewart\" = c(\"GS\", \"PHD\"))

我对 Bob、Steward、Kevin 进行了 rbind,我将如何输出如下所示的表格: 我尝试在变量度量上创建 rownams,但不确定如何保留不同的列名并将它们加粗。

谢谢!

    标签: html r html-table format r-markdown


    【解决方案1】:

    这是tidyverse flextable 解决方案:

    1. 绑定两个 tibbles 后,我们使用 coalesce 创建 Variables 列。

    2. 我们按 2 行分组,并使用 select 将 tibble 调整为形状

    3. 我们使用group_modify 在每个组的首位添加一行

    4. 使用case_when 语句,我们硬编码名称DoBEducation

    5. 下一部分是使用flextable 获取粗体列名和行名。

      library(tidyverse)
      library(flextable)
      
      bind_rows(tibble1, tibble2) %>% 
        mutate(Variables = coalesce(DoB, Education)) %>% 
        group_by(group =as.integer(gl(n(),2,n()))) %>% 
        select(Variables, Bob, Kevin, Stewart, group) %>% 
        group_modify(~ add_row(.x,.before=0)) %>% 
        mutate(Variables = case_when(is.na(Variables) & group == 1 ~ "DoB",
                                     is.na(Variables) & group == 2 ~ "Education", 
                                     TRUE ~ Variables)) %>% 
        ungroup() %>% 
        select(-group) %>% 
        flextable() %>% 
        bold(bold = TRUE, part = "header") %>% 
        bold(i = ~ Variables %in% c("DoB", "Education"), bold = TRUE)
      

    【讨论】:

    • 谢谢!这对我想要的东西非常有帮助——跟进:如果我有不同长度的组,我怎么能把它添加进去?例如。这些组每个有 2 个组,但是如果我添加到一个有 3 个子组的组中呢?
    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多