【问题标题】:Error in eval(predvars, data, env) : object 'Practice' not foundeval 中的错误(predvars,data,env):找不到对象“练习”
【发布时间】:2022-01-11 01:37:20
【问题描述】:

我有下面的代码,但是执行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)

我想同时打印pvaluetab,这是我得到的错误

有没有改正的可能?

【问题讨论】:

  • 函数table1没有定义,能不能发一下或者我们能找到的包?
  • library(table1) 好的,我在帖子里加了

标签: r function


【解决方案1】:

基本函数table 没有找到变量,它们必须从数据中提取,但不能使用运算符$,请参阅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%)

编辑

使用新测试,cochran.test 出现错误。
下面更新的函数运行两个测试,Cochran 的 tryCatch 并输出错误消息。

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)
}

【讨论】:

  • 是的,谢谢,它是这样工作的,但是当我更改测试时,例如 cochran test 我给出了同样的错误,我在帖子上添加了 cochran 的代码
  • @Ruser-lab9 查看编辑。如果我太复杂了,请说出来,我会再次编辑。
猜你喜欢
  • 2018-11-05
  • 2020-09-21
  • 2020-04-12
  • 1970-01-01
  • 2020-04-02
  • 2019-01-31
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
相关资源
最近更新 更多