R语言for循环遍历多列绘制boxplot箱线图报错如何解决?
错误原因
- 遍历得到的
i是字符串类型的列名,boxplot()的公式语法默认会把公式中的标识符直接作为数据框的列名搜索,不会自动解析字符串变量对应的实际列名 all_of()是tidyverse生态下dplyr选列的专属语法,base R的公式接口不支持该用法,直接使用会导致变量匹配错误
解决方案1:动态构造公式
用as.formula()把拼接好的公式字符串转为公式对象即可,修改后的循环代码如下:
looper <- c("est1", "est2", "est3", "est4", "est5", "est6") counter <- 0 for (i in looper){ counter <- counter +1 # 动态构造公式 form <- as.formula(paste(i, "~ real")) boxplot(form, data=df, main = paste("Estimated Probability for Category",counter,"Given the Real Categories") ) }
解决方案2:直接传入绘图向量(无需公式)
boxplot()支持直接传入绘图的向量变量,更适合循环场景:
looper <- c("est1", "est2", "est3", "est4", "est5", "est6") counter <- 0 for (i in looper){ counter <- counter +1 # 直接从数据框提取对应列绘图 boxplot(df[[i]] ~ df$real, main = paste("Estimated Probability for Category",counter,"Given the Real Categories"), xlab = "real", ylab = i ) }
内容的提问来源于stack exchange,提问作者rtuh
相关产品推荐
相关产品推荐

