r语言 - "for loop"中的箱线图:将字符串转换为变量



我试图从数据帧绘制箱线图,并分别保存每个箱线图的图像,但得到错误。在代码的第4行,我相信"x"是字符串而不是变量。那么,我应该如何将这个字符串转换为循环变量呢?

(i)示例数据帧:

df <- data.frame(var1=c(1, 3, 3, 4, 5), 
var2=c(7, 7, 8, 3, 2),
type=factor(c('A','B','B','C','D'))) #dataframe
(ii)查询示例:
LIST<-c('var1', 'var2')

(iii)执行的守则

for (j in LIST) #
{
png(print(paste0((j),".png")))
boxplot(as.numeric(paste("df",j, sep = "$")) ~ as.factor(df$type))  #..(4)
dev.off()
}

(iv)错误信息

Error in stats::model.frame.default(formula = as.numeric(paste("df$",  : 
variable lengths differ (found for 'as.factor(df$type)')
In addition: Warning message:
In eval(predvars, data, env) : NAs introduced by coercion

您的代码比需要的多。试试这个

for (j in LIST) #
{
png(paste0(j, ".png"))
boxplot(df[, j] ~ df$type)
dev.off()
}

最新更新