我有一个列的列表,其编号属于每个类别
list.group <-list(list(id = 2, type = "num"), list(id = 3, type = "num"),
list(id = 4, type = "cat"), list(id = 5, type = "cat"))
我有一个函数,其中对于类型为“num”的列有 2 个测试(wilcox 测试和 Fisher 测试),我希望执行 wilcox 测试,对于类型“cat”,执行 Fisher 测试。
首先,我将一个列表分为 2 个列表(列列表和类别列表):
w = unlist(list.group, recursive = TRUE)
w.length = length(w)
col.id = w[seq(1,w.length,2)]
col.type = w[seq(2,w.length,2)]
col.id = as.integer(col.id)
col.type = as.character(col.type)
功能:
combination <- list(c(3,24),c(3,14))
wilcox.fun <- function(df, id_group){
df = df[df$GROUP%in%id_group,]
x <- function(dat) {
do.call(rbind, lapply(combination, function(x) {
if(col.type=="num"){
test <- wilcox.test(dat[[x[1]]], dat[[x[2]]])}
if(col.type=="cat"){
test1 <- fisher.test(dat[[x[1]]], dat[[x[2]]])}
data.frame(Test = sprintf('Group %s by Group %s Group',x[1],x[2]),
#W = round(test$statistic,4),
p = test$p.value,
p1 = test1$p.value,
#median=paste(x[1],median.group.1,x[2],median.group.2),
nmat = table(dat[[x[1]]]),
nmat1 = round((prop.table(table(dat[[x[1]]]), 1) * 100), 1),
nmat2=table(dat[[x[2]]])
)
}))
}
return (purrr::map_df(split(df, df$GROUP),x,.id="GROUP" ))
}
数据框:
data <- structure(list(GROUP = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L),
col1 = c(23L, 432L, 234L, 234L, 3123L, 657L, 8768L, 123L,
42323L), col2 = c(567L, 765L, 8678L, 46L, 35L, 24L, 76L,
789L, 45L), col3 = c(1L, 3L, 5L, 7L, 8L, 0L, 8L, 7L, 3L),
col4 = c("S", "S", "S", "S", "F", "F", "F", "F", "F")), class = "data.frame", row.names = c(NA,
-9L))