I have the code below, but I have error when executing the FUN
function
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)
I want to print both pvalue
and tab
, and this is the error I got
is there any possibility to correct it ?
CodePudding user response:
Base function table
is not finding the variables, they must be extracted from the data but not with the operator $
, see this SO post.
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%)
Edit
With the new test, cochran.test
there is an error.
The updated function below runs both tests, Cochran's with tryCatch
and the error message is output.
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)
}