Home > Blockchain >  Boxplots in "for loop": Transforming character string to a variable
Boxplots in "for loop": Transforming character string to a variable

Time:06-05

I am trying to plot boxplots from a data frame, and save the image of each boxplot separately, but get the error. In line 4 of code, I believe the "x" is a character string and not a variable. So, how should I transform this character string to a loop variable?

(i) Example dataframe:

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) Example query:

LIST<-c('var1', 'var2')

(iii) Code implemented

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 message

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

CodePudding user response:

You have more code than you need. Try this

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