sub function to replace values from etable

55 Views Asked by At

I have a etable from expss output now i want to replace values from tables to "*" as per the total value

for example if the total is 5 then replace Ave to "" , if total <= 4 then replace Max to "" , if total is <= 3 the replace Min to "*"

library(expss)
library(dplyr)

df <- mtcars
df$vs <- 1
banner1 <- list(df$vs)
Grace_1 = 3
Grace_2 = 4
Grace_3 = 5

Average <- function(x) mean_col(x, na.rm = TRUE)
Min <- function(x) min_col(x, na.rm = TRUE)
Max <- function(x) max_col(x, na.rm = TRUE)
t1 <- cross_fun(df, df$hp, col_vars = banner1,
                fun = combine_functions(Max = Max, Min = Min,Ave = Average, Total = valid_n))

should be look like, below table is just a example

enter image description here

enter image description here

1

There are 1 best solutions below

0
On

To achieve your desired result you could use a case_when to replace the values in your table conditional on the total value.

Note: For your example data the total value in your table is 32. Hence, I use a hard-coded 5 to illustrate your rule.

library(expss)
library(dplyr, warn=FALSE)

df <- mtcars
df$vs <- 1
banner1 <- list(df$vs)

Average <- function(x) mean_col(x, na.rm = TRUE)
Min <- function(x) min_col(x, na.rm = TRUE)
Max <- function(x) max_col(x, na.rm = TRUE)
t1 <- cross_fun(df, df$hp,
  col_vars = banner1,
  fun = combine_functions(Max = Max, Min = Min, Ave = Average, Total = valid_n)
)

# Fix total for illustartion as the total in the table = 32
total <- 5#t1[["1"][4]
            
t1[["1"]] <- case_when(
  total <= 3 & grepl("Min$", t1[["row_labels"]]) ~ "*",
  total <= 4 & grepl("Max$", t1[["row_labels"]]) ~ "*",
  total == 5 & grepl("Ave$", t1[["row_labels"]]) ~ "*",
  .default = as.character(t1[["1"]])
)

print(t1)
#>                         
#>  |       |       |   1 |
#>  | ----- | ----- | --- |
#>  | df$hp |   Max | 335 |
#>  |       |   Min |  52 |
#>  |       |   Ave |   * |
#>  |       | Total |  32 |