R运行自定义Fun函数提示object 'Practice' not found如何解决
R代码报错修正方案
报错原因
函数内部公式默认从执行环境中搜索变量,你直接传入全局变量名作为参数时,函数无法识别这些参数对应数据框内的列,因此抛出找不到对象的错误。
修正后完整代码
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_col, resp_col, id_col) { # 动态构造table1公式 tab_formula <- as.formula(paste0("~ ", resp_col, " | ", var_col)) tab <- table1(tab_formula, data = data, topclass = "Rtable1-zebra") tab <- as.data.frame(tab) # 动态构造Cochran Q检验公式 test_formula <- as.formula(paste0(resp_col, " ~ ", var_col, " | ", id_col)) test <- cochran.qtest(test_formula, data = data) pvalue <- test$p.value # 命名列表返回结果,便于后续调用 return(list(p_value = pvalue, table_result = tab)) } # 调用函数,传入列名字符串 output <- Fun(dataset, "Practice", "Response", "Student")
结果调取方式
- 获取p值:
output$p_value - 获取生成的表格:
output$table_result
核心修改点
- 将硬编码的公式改为通过
as.formula动态拼接,函数可正确匹配传入的列名和数据框内的字段,解决对象找不到的报错 - 替换原返回逻辑中的
c()为标准list()结构,避免p值和表格数据被强行合并破坏结构,同时给返回元素命名方便调取
内容的提问来源于stack exchange,提问作者Ruser-lab9
相关产品推荐
相关产品推荐

