Friday, March 8, 2013

RGui, Rstudio, Notepad++; Creating and Using Functions

The code below is from the youtube published screen cast above. This screen cast is available as a high resolution WMV file. For more data see the Week4 folder.

# * ** Basic R Programming Function and Plotting Demonstration ** * #

# create a function to find the square of any number
sqr <- function(a) {a^2}
# works on 'scalar' or iterates over 'vector'
sqr(100)
sqr(1:100)
# use 'sapply' to iterate range as a data.frame for your function 'sqr' and built-in function 'sqrt'
data.frame(sapply((1:100),sqr))
data.frame(sapply((1:100),sqr),(sapply((1:100),(sqrt))))
# plot the data.frame as a histogram with custom X,Y labels
plot(data.frame(sapply((1:100),sqr),(sapply((1:100),(sqrt)))),xlab="Square 1:100", ylab="Square root 1:100",type="h")

# use 'cbind' (column bind) to apply XY labels to the columns
data.frame(cbind(sqr=sapply((1:100),sqr)),sqrt=sapply((1:100),(sqrt)))
# pump the same dataframe  to 'dd' and plot 'dd'
dd <- data.frame(cbind(sqr=sapply((1:100),sqr)),sqrt=sapply((1:100),(sqrt)))
plot(dd, type="h")
lines(dd)

# create separate numeric vectors and combine them into a dataframe
s1 <- sapply((1:100),sqr)
s2 <- sapply((1:100),sqrt)
dd <- data.frame(s1,s2)
plot(dd, type="h")
lines(dd)

# use terms more relevant to the X and Y labels
Square <- sapply((1:100),sqr)
SquareRoot <- sapply((1:100),sqrt)
dd <- data.frame(Square,SquareRoot)
plot(dd, type="h")
lines(dd)

# create functions and values for all XY graph quadrants
sqr <- function(a) {a^2}
sqr_neg <- function(a) {-(a^2)}

Square <- sapply((1:100),sqr)
Square_neg <- -(sapply((1:100),sqr))
SquareRoot <- sapply((1:100),sqrt)
SquareRoot_neg  <- -(sapply((1:100),sqrt))

 # plot a four by four series of charts as a dataframe
dd <- data.frame(Square,SquareRoot,Square_neg,SquareRoot_neg)
plot(dd)

#quadrant (both XY are positive numbers)
plot(dd$Square,dd$SquareRoot, type="h")
lines(dd$Square,dd$SquareRoot)

# quadrant (both XY are negative numbers)
plot(dd$Square_neg,dd$SquareRoot_neg, type="h")
lines(dd$Square_neg,dd$SquareRoot_neg)

 # use points instead of lines
plot(dd$Square,dd$SquareRoot, type="h")
points(dd$Square,dd$SquareRoot)

plot(dd$Square_neg,dd$SquareRoot_neg, type="h")
points(dd$Square_neg,dd$SquareRoot_neg)

# More Plotting and plotting functions
plot(Square ~ SquareRoot)

plot(Square,SquareRoot)
plotfunc <- function(x) {plot((Square ~ SquareRoot),subset = x)}
plotfunc <- function(x) {plot((Square ~ SquareRoot),dd,subset = x)}
plotfuncSquaregtr <- function(x) {plot((Square ~ SquareRoot),subset=Square > x)}
plotfuncSquarelt <- function(x) {plot((Square ~ SquareRoot),subset=Square < x)}


No comments: