R语言 替换etable中的值的子函数

osh3o9ms  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

我有一个从expss输出etable现在我想从表中替换值为“”作为每一个总的价值
例如,如果总数为5,则将Ave替换为“
”,如果总数<= 4,则将Max替换为“”,如果总数<= 3,则将Min替换为“

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))

字符串
下面表格只是一个例子


的数据


rkue9o1l

rkue9o1l1#

为了达到你想要的结果,你可以使用case_when来替换表中的值,条件是总值。
注意:对于您的示例数据,表中的总值为32。因此,我使用硬编码的5来说明您的规则。

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 |

字符串

相关问题