views:

422

answers:

2

I previously asked this question which was useful in plotting a function. I want to try and plot twenty functions on the same axes to illustrate how a function varies between two ranges. I have successfully done this using individually specified functions, but I wanted to do this using a loop.

What I have attempted doing is:

## add ggplot2
library(ggplot2)
library(lattice)

# Declare local variables
inPath = "D:/R_Analysis/"
inFile = "sample.txt"

outPath = "D:/R_Analysis/"
outFile = "processed_sample.txt"

pdfOutPath = "D:/R_Analysis/"
pdfOutFile = "processed_sample.pdf"

# Declare Chart values
y_label = "x-axis"
x_label = "y-axis"
chart_title = "..." 

#####################################################################
## Read in data;  
analysis <- 
read.table(paste(inPath, inFile, sep=""), header=TRUE, sep=",", 
na.strings="NA",  dec=".", strip.white=TRUE)

# Setup pdf
pdf(paste(pdfOutPath, pdfOutFile, sep=""),height=6,width=9)

# make plot object    
p <- qplot(
data = data.frame(x = x, y = y), x, y, xlab = x_label, ylab = y_label, 
enter code herexlim = x_range, main = chart_title  )

# make empty function
eq_dummy = function(x){ 0 }
d = stat_function(fun = eq_dummy)

##############
# LOOP #######

for(i in 1 : 21){                                            

        # Specify Variables
        intercept = analysis[i,2]
        slope = analysis[i,3]    

        # Define Curve    
        eq <- function(x) { slope * log(x) + intercept }

        # Make plot object            
        composite <- stat_function(fun=eq)        
        composite = composite + d       

}

print(p + composite)  

# Show warnings
warnings()

# close the PDF file
dev.off() 

Any suggestions about syntax improvement, or programming structure would be appreciated. Thank you.

+2  A: 

There is nice function file.path which allow to create file paths OS independent. You could use it in your code as:

inPath = file.path("D:","R_Analysis")
inFile = "sample.txt"
outPath = file.path("D:","R_Analysis")
outFile = "processed_sample.txt"
pdfOutPath = file.path("D:","R_Analysis")
pdfOutFile = "processed_sample.pdf"

and then use

read.table(file.path(inPath, inFile))
pdf(file.path(pdfOutPath, pdfOutFile))

Your path is "windows-depended" (reference to disk label), but if you use relatives paths then it could be more useful.

And second hint - you should open graphics device as late as possible, e.g.

pdf(file.path(pdfOutPath, pdfOutFile),height=6,width=9)
print(p + composite)  
dev.off()

Then it's easier to search for proper line when you want to see plot in window and not in file.

Marek
A: 

Be consistent with your style. For example, always use <-, or always use =; don't mix and match. Here are some example style guides from Google and Hadley Wickham.

If you are using read.table with sep=',' and header=TRUE, you can probably call read.csv instead.

Wherever possible, try to place things in functions rather than having one long script. This can help make the code more readable, and as a bonus you may end up with bits of code you can reuse for later analyses. In this case, I'd be tempted to move all the code that creates the plot into a function (possibly with subfunctions for initialising the plot and for doing the drawing part).

The R Inferno contains lots of ideas on good R programming practice.

Richie Cotton