R Markdown knit时报object of type 'closure' is not subsettable错误求助
问题根因
- 核心触发点:你使用了R内置转置函数的名称
t作为存储结果的列表名,且没有提前初始化该对象。R中t默认是函数(属于closure类型),交互式运行时你大概率提前创建过名为t的列表,所以运行正常;但knit导出时会启动全新的干净运行环境,直接执行t[[i]] <- ...会调用内置的t函数,函数对象无法用[[进行子集赋值,就触发了对应报错。 - 潜在稳定隐患:
tabyl()默认采用非标准求值,直接传入字符串变量i可能在部分环境下无法正确识别对应数据列。
解决方案
推荐优先采用以下修改方式,从根源避免冲突:
- 更换存储结果的对象名,避开R内置函数名(比如改为
t_res),且提前初始化为空白列表 - 调整
tabyl()传参逻辑,用.data[[i]]明确指定要统计的列,适配字符串传参场景
如果不想更换变量名,也可以在循环前执行t <- list()手动初始化列表,覆盖内置的t函数即可解决报错,但不推荐该方式,容易后续引发其他命名冲突。
修改后可正常knit的代码
library(tidyverse) library(janitor) id <- c("001", "002", "003") Gender <- c(0,1,1) Insurance <- c(1,0,0) Employment <- c(0,1,0) Stroke <- c(1,1,0) sample <- tibble(id, Gender, Insurance, Employment, Stroke) sample vbles <- c("Gender", "Insurance", "Employment", "Stroke") # 提前初始化结果列表,避开内置函数名 t_res <- list() for (i in vbles){ t_res[[i]] <- sample %>% tabyl(.data[[i]]) %>% select("percent") } test <- matrix(c(t_res$Gender[1,], t_res$Insurance[1,], t_res$Employment[1,], t_res$Stroke[1,],t_res$Gender[2,], t_res$Insurance[2,], t_res$Employment[2,], t_res$Stroke[2,]), ncol=2, byrow=FALSE) rownames(test) <- c("Gender", "Insurance", "Employment", "Stroke") colnames(test) <- c(0,1) test <- as.table(test) test
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

