从expss R包在etable中添加行
我想将特定位置的行添加到从expss R包在etable中添加行,r,tidyverse,expss,R,Tidyverse,Expss,我想将特定位置的行添加到expssoutputetable。我使用了一些蛮力方法,总是在etable的开头添加行。在特定位置添加行的任何方法 library(tidyverse) library(expss) test1 <- mtcars %>% tab_cells(cyl) %>% tab_cols(vs) %>% tab_stat_cpct() %>% tab_pivot() test1 %>%
expss
outputetable
。我使用了一些蛮力方法,总是在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)
库(tidyverse)
图书馆(expss)
测试1%
tab_单元格(气缸)%>%
表列(vs)%>%
tab_stat_cpct()%>%
tab_pivot()
测试1%>%
tibble()%>%
tibble::添加_行(.data=tibble(“,test1[2,-1]/test1[1,-1]*100)%
设置名称(名称(test1))
,.before=3)
不确定是否有使用expss
导出的简单方法,但我们可以使用expss::add_rows()
和一个简单的自定义函数拆分表来完成此操作
insert_row基于@calwellst代码但具有自动比率计算的解决方案:
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
insert_ratio 1)| | stop(“'where'对于比率计算应该大于1”)
isTRUE(其中1)| | stop(“'where'对于比率计算应大于1”)
isTRUE(感谢您提供了一个很好的解决方法。想知道如何使用test1[2,-1]/test1[1,-1]*100
而不是输入300,40
。太好了!我们可以在函数之外进行计算吗?
ratio = function(tbl, where, label = NULL){
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.")
if(is.null(label)) label = tbl[[1]][where]
c(row_labels = label, tbl[where, -1]/tbl[where - 1, -1]*100)
}
insert_row = function(tbl, where, row) {
if(is.character(where)) {
# if where is character we search it in the rowlabels
where = grep(where, tbl[[1]], 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, 2, ratio(test1, 2))
insert_row(test1, "cyl|6", ratio(test1, "cyl|6"))