user3292755
user3292755

Reputation: 423

looping a data frame to create a boxplot

i'm trying to get boxplot using R software in a data frame but there are lots of columns attached to the data frame. Here is the code

path = "E:/plot/2"
fileList = list.files(path=path,pattern="\\.teTestResult",full.names=T)
myfiles = lapply(fileList, read.csv,header=TRUE,sep=";" )

a <- data.frame(myfiles)
attach(a)
boxplot(Return~gama)
boxplot(Return~theta)
boxplot(Return~detectionsLimit)
boxplot(Return~NSMOOTH)
boxplot(Return~NREF)
boxplot(Return~NOBS)
boxplot(Return.1~gama.1)
boxplot(Return.1~theta.1)
boxplot(Return.1~detectionsLimit.1)
boxplot(Return.1~NSMOOTH.1)
boxplot(Return.1~NREF.1)
boxplot(Return.1~NOBS.1)
...
boxplot(Return.9~NOBS.9)

This code works, but it did not deliver a good one because it is very long. How can i simplify this using R? Thank you so much for the help

~Update~

I'm trying to use the for loop because the variable name im trying to boxplot only differs in the number, so here it is

for (i in 1:9){
boxplot(Return.[i]~gama.[i])
    }

But, an error occured saying this

Error in eval(expr, envir, enclos) : object 'Return.' not found 

I'm still witnessing much problems with R programming Thank you so much for your replies.

Upvotes: 0

Views: 119

Answers (1)

MarkusN
MarkusN

Reputation: 3223

if you combine the list of dataframes with data.frame() function, you are cbind-ing the dataframes. if all the files are of the same structure I'd suggest you combine them using rbind:

library(dplyr)
for(i in 1:length(myfiles)) myfiles[[i]]$nr = i   # if you need to know the origin of the data
df = bind_rows(myfiles)

The distinction between the different files can be done by faceting, but since you need plots for different variables you probably can't shorten your code any further:

library(ggplot2)
ggplot(df, aes(factor(gama), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(theta), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(detectionsLimit), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NSMOOTH), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NREF), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NOBS), Return)) + geom_boxplot() + facet_wrap(~ nr)

Upvotes: 1

Related Questions