sub function to replace values from etable

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

image

image

Hi @str_guru. Admittedly not the most elegant solution, but below is a function that replaces the values as you specify. Please note, the function follows the description where two of the three cases are replaced with empty characters "" (but the examples provided replace everything with "*").

library(stringr)

# function to replace values
replace_values = function(i) {
  
  # identify position of each category of interest (Max, Min, etc.) in vector
  mymax = which(str_detect(i$row_labels, 'Max'))
  mymin = which(str_detect(i$row_labels, 'Min'))
  myave = which(str_detect(i$row_labels, 'Ave'))
  mytotal = which(str_detect(i$row_labels, 'Total'))
  out = i
  
  Total = out$`1`[mytotal]
  
  # preserve formatting
  out$`1` = sprintf("%.1f", round(out$`1`,1))
  
  # check and overwrite if true
  if(Total == 5) {out$`1`[myave] = ''}
  if(Total <= 4) {out$`1`[mymax] = ''}
  if(Total <= 3) {out$`1`[mymin] = '*'}
  
  out
}

t1

image

# Sample case (force Total = 5)
t2 = t1 
t2$`1`[4] = 5
t2 |> replace_values()

image

# Sample case (force Total <= 4)
t3 = t1 
t3$`1`[4] = 3.5
t3 |> replace_values()

image

Created on 2023-12-15 with reprex v2.0.2

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.