管理输出摘要中的十进制值

问题描述

样本数据:

dataa<-data.frame(
  aa = c("q","r","y","v","g","d","s","n","k","t","u","l","h","x","c","q","c"),col1=c(1,2,3,1,4,5,5),col2=c(2,7,6,4)
)

sum

解决方法

您可以尝试使用此功能:

library(expss)
library(flextable)
library(dplyr)
library(rlang)

tab_std_cross <- function(dat1,var1,grouping_var){
  
  var1 <- parse_expr(var1)
  var2 <- parse_expr(grouping_var)
  
  dat2 <- dat1 %>% select(!!var1,!!var2)
  var_lab(dat2[[1]]) <- ""
  var_lab(dat2[[2]]) <- ""
  tab1 <- cro_cpct(dat2[[1]],dat2[[2]]) 
  tab1 <- as.data.frame(tab1)
  tab1[which(tab1[,1]=="#Total cases"),1] <- "N"
  tab1[is.na(tab1)] <- 0
  tab1 <- tab1 %>%
    mutate(
      across(
        .cols = where(is.numeric),.fns = ~ round(.x,digits = 1)
      )
    )
  tab1[tab1 == 0] <- '--' # --- (1)
  mask_indices <- sapply(tab1,function(x) x[length(x)] %in% c(3,4,5)) %>%
    which()  
  tab1[,mask_indices] <- "--"
  tab1[-nrow(tab1),-c(1,mask_indices)] <- sapply(
      tab1[-nrow(tab1),mask_indices)],function(x) # --- (2)
    ifelse(x != '--',paste(format(as.numeric(x),nsmall = 1),"%"),x)) # --- (3)
  tab1 <- flextable(tab1)
  tab1
}

该功能已更改:

  1. "--"替换所有0值
  2. 已将第1列从"%"删除,因为没有必要在行标签上添加"%"
  3. 使用ifelse来避免将"--"变成"-- %"。 仅显示数字直到小数点后一位。
tab_std_cross (dat1 = dataa,var1 = "col1",grouping_var="col2")

enter image description here