如何解决在expss R包中的etable中添加行
我想在expss
输出etable
的特定位置添加行。我使用某种蛮力方法做到了这一点,该方法总是将行添加到etable
的开头。在特定位置添加行的任何方法。
library(tidyverse)
library(expss)
test1 <-
mtcars %>%
tab_cells(cyl) %>%
tab_cols(vs) %>%
tab_stat_cpct() %>%
tab_pivot()
test1 %>%
tibble() %>%
tibble::add_row(.data = tibble("",test1[2,-1]/test1[1,-1]*100) %>%
set_names(names(test1)),.before = 3)
解决方法
不确定expss
导出了一个简单的方法,但是我们可以将expss::add_rows()
与一个简单的自定义函数一起使用来拆分表以实现此目的。
insert_row <- function(tbl,where,...) {
args <- c(...)
tbl1 <- tbl[1:where,]
tbl2 <- tbl[(where+1):nrow(tbl),]
tbl1 %>%
add_rows(args) %>%
add_rows(tbl2)
}
insert_row(test1,2,c("cyl|4",300,40))
| | | vs | |
| | | 0 | 1 |
| --- | ------------ | ---------------- | ---------------- |
| cyl | 4 | 5.55555555555556 | 71.4285714285714 |
| | 6 | 16.6666666666667 | 28.5714285714286 |
| | 4 | 300 | 40 |
| | 8 | 77.7777777777778 | |
| | #Total cases | 18 | 14 |
,
基于@caldwellst代码但具有自动比率计算的解决方案:
insert_ratio <- function(tbl,where) {
if(is.character(where)) {
# if where is character we search it in the rowlabels
where = grep(where,tbl[[1]],fixed = TRUE)[1]
}
isTRUE(where>1) || stop("'where' should be greater than 1 for ratio calculation.")
isTRUE(where<=NROW(tbl)) || stop("'where' should be less or equal than number of rows in the table.")
tbl1 <- tbl[1:where,]
to_insert = c(row_labels = tbl[[1]][where],tbl[where,-1]/tbl[where - 1,-1]*100)
tbl2 <- tbl[(where+1):nrow(tbl),]
tbl1 %>%
add_rows(to_insert) %>%
add_rows(tbl2)
}
insert_ratio(test1,2)
# | | | vs | |
# | | | 0 | 1 |
# | --- | ------------ | ----- | ---- |
# | cyl | 4 | 5.6 | 71.4 |
# | | 6 | 16.7 | 28.6 |
# | | | 300.0 | 40.0 |
# | | 8 | 77.8 | |
# | | #Total cases | 18.0 | 14.0 |
insert_ratio(test1,"cyl|6")
# the same result
更新 比率计算移至单独的功能:
ratio = function(tbl,label = NULL){
if(is.character(where)) {
# if where is character we search it in the rowlabels
where = grep(where,fixed = TRUE)[1]
}
isTRUE(where>1) || stop("'where' should be greater than 1 for ratio calculation.")
isTRUE(where<=NROW(tbl)) || stop("'where' should be less or equal than number of rows in the table.")
if(is.null(label)) label = tbl[[1]][where]
c(row_labels = label,-1]*100)
}
insert_row = function(tbl,row) {
if(is.character(where)) {
# if where is character we search it in the rowlabels
where = grep(where,fixed = TRUE)[1]
}
isTRUE(where<=NROW(tbl)) || stop("'where' should be less or equal than number of rows in the table.")
first_part = seq_len(where)
tbl1 <- tbl[first_part,]
tbl2 <- tbl[-first_part,]
tbl1 %>%
add_rows(row) %>%
add_rows(tbl2)
}
insert_row(test1,ratio(test1,2))
insert_row(test1,"cyl|6","cyl|6"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。