【发布时间】:2022-01-12 12:02:25
【问题描述】:
我正在与 R 合作。
鉴于我生成的以下随机数据,我能够用这些数据制作一个列联表:
library(memisc)
library(dplyr)
set.seed(123)
v1 <- c("2010-2011","2011-2012", "2012-2013", "2013-2014", "2014-2015")
v2 <- c("A", "B", "C", "D", "E")
v3 <- c("Z", "Y", "X", "W" )
v4 <- c("data_1", "data_2", "data_3", "data_4" )
dates <- as.factor(sample(v1, 1000, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))
types <- as.factor(sample(v2,1000, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))
types2 <- as.factor(sample(v3, 1000, replace=TRUE, prob=c(0.3, 0.5, 0.1, 0.1)))
names <- as.factor(sample(v3, 1000, replace=TRUE, prob=c(0.3, 0.5, 0.1, 0.1)))
var = rnorm(1000,10,10)
problem_data = data.frame(var,dates, types, types2, names)
summary <- xtabs(~dates+names+types+types2, problem_data)
t = ftable(summary, row.vars=1, col.vars=2:4)
show_html(t)
是否可以直接从数据框中制作类似于表的列联表?
例如,假设我想制作上面的列联表,但我不想用“counts”填充这个表,而是用“var”的平均值来填充这个表。使用“dplyr”库,我可以创建一个包含此列联表所需的所有值的数据框:
library(dplyr)
contingency_table = data.frame(problem_data %>% group_by(dates,names, types, types2) %>% summarise(mean_value = mean(var)))
head(contingency_table)
dates names types types2 mean_value
1 2010-2011 W A X -10.128687
2 2010-2011 W A Y 9.552724
3 2010-2011 W A Z 9.686354
4 2010-2011 W B W -4.411400
5 2010-2011 W B Y 13.624970
6 2010-2011 W B Z 7.008089
可以把上面这个数据框做成列联表,然后转换成html可发布的格式吗?
在此处使用此 stackoverflow 帖子 (Is there an (easy) way to convert flat contingency tables (ftable) to flextable),我尝试使用提供的函数将此数据帧转换为列联表 - 但它没有给出所需的结果(即它与表不同以上):
ftable_to_flextable <- function( x ){
row.vars = attr( x, "row.vars" )
col.vars = attr( x, "col.vars" )
rows <- rev( expand.grid( rev(row.vars), stringsAsFactors = FALSE ) )
cols <- rev(expand.grid( rev(col.vars), stringsAsFactors = FALSE ))
xmat <- as.matrix(x)
cols$col_keys = dimnames(xmat)[[2]]
xdata <- cbind(
data.frame(rows, stringsAsFactors = FALSE),
data.frame(xmat, stringsAsFactors = FALSE)
)
names(xdata) <- c(names(row.vars), cols$col_keys)
ft <- regulartable(xdata)
ft <- set_header_df(ft, cols)
ft <- theme_booktabs(ft)
ft <- merge_v(ft, j = names(row.vars))
ft
}
library(flextable)
library(magrittr)
ftable(contingency_table, row.vars = 1:2, col.vars = 3:4) %>% ftable_to_flextable()
是否可以制作一个列联表,而不是计数,而是使用每个组的变量“var”的平均值?使用 xtabs() 函数是否更好,而我使用“数据框方法”使这变得过于复杂?有人可以告诉我怎么做吗?
谢谢!
【问题讨论】:
标签: r dplyr html-table data-manipulation