我有下面的代碼,但在執行FUN函式時出錯
library(table1)
library(RVAideMemoire)
Practice<-c(rep("Clippings",14),rep("Irrigation",14),rep("MowHeight",14),rep("SoilTest",14))
Response<-c(rep("No",23),rep("Yes",33))
Student<-c(rep("a",4),rep("b",4),rep("c",4),rep("d",4),rep("e",4),rep("f",4),rep("g",4),rep("h",4),rep("i",4),rep("j",4),rep("k",4),rep("l",4),rep("m",4),rep("n",4))
dataset<-data.frame(Practice,Student,Response)
Fun<-function(data,var,Response,ID) {
tab<-table1(~ Response | var, data=data,topclass="Rtable1-zebra")
tab<-as.data.frame(tab)
test<-cochran.qtest(Response ~ var | ID,data = data)
pvalue<-test$p.value
list<-c(pvalue,tab)
return(list)
}
Fun(dataset,Practice,Response,Student)
我想同時列印pvalue和tab,這是我得到的錯誤

有沒有可能糾正它?
uj5u.com熱心網友回復:
基函式table沒有找到變數,它們必須從資料中提取,而不是使用運算子$,請參閱此 SO 帖子。
Fun <- function(data, var, Response, ID) {
v <- deparse(substitute(var))
r <- deparse(substitute(Response))
tab <- table1(~ Response | var, data=data, topclass = "Rtable1-zebra")
tab <- as.data.frame(tab)
tbl <- table(data[[v]], data[[r]])
test <- chisq.test(tbl)
pvalue <- test$p.value
list(p.value = pvalue, table = tab)
}
Fun(dataset, Practice, Response, Student)
#$p.value
#[1] 2.82287e-09
#
#$table
# Clippings Irrigation MowHeight SoilTest Overall
#1 (N=14) (N=14) (N=14) (N=14) (N=56)
#2 Response
#3 No 14 (100%) 9 (64.3%) 0 (0%) 0 (0%) 23 (41.1%)
#4 Yes 0 (0%) 5 (35.7%) 14 (100%) 14 (100%) 33 (58.9%)
編輯
用新的測驗,cochran.test有錯誤。
下面更新的函式運行兩個測驗,Cochran's withtryCatch并輸出錯誤訊息。
Fun <- function(data, var, Response, ID) {
v <- deparse(substitute(var))
r <- deparse(substitute(Response))
tab <- table1(~ Response | var, data=data, topclass = "Rtable1-zebra")
tab <- as.data.frame(tab)
tbl <- table(data[[v]], data[[r]])
test1 <- chisq.test(tbl)
test2 <- tryCatch(
cochran.qtest(Response ~ var | ID, data = data),
error = function(e) e
)
pv2 <- if(inherits(test2, "error"))
paste("Error:", conditionMessage(test2))
else test2$p.value
pvalue <- list(test1$p.value, pv2)
pvalue <- setNames(pvalue, c("chisq", "cochran"))
list(p.value = pvalue, table = tab)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/372987.html
