Tuesday, May 27, 2014

Data analysis using R - R programming Tutorial ( Part 4 )

 

Script Editor

The script editor is used for writing programs in R.
To start a new script, click File>New Script
The easiest way to run code is keyboard shortcuts
I To run part of a program, highlight the lines you want and hit Ctrl+R
I To run an entire program, select all the code then run, Ctrl+A then
Ctrl+R


When you save a script file in R you need to include the .R extension, R
doesn’t automatically add the file type.
You don’t need semi-colons at the end of each line. However, if you enter
more than one expression on the same line you will need semi-colons.
You can wrap a long expression onto several lines, but you need to be careful
that R does not treat your unfinished code as a complete expression.
To comment a line of code use a #. There is no block commenting in R.
Commenting Code
Comments are notes that help users understand portions of your code. They are
also useful reminders to yourself of what was done and why it was done.
Including meaningful comments in code is a major part of writing good programs.

# Calculate the mean of x
> x = c(0,5,7,9,1,2,8)
> mean(x)
# How and how not to wrap expressions
> long.variable.name <- 5
> really.long.variable.name <- 7
# R views the first line as a complete expression. Thus the code is
# treated as two separate expressions instead of one long expression.
> long.answer.name <- 500*factorial(long.variable.name)
+ sqrt(really.long.variable.name)
# Here the first line is not a complete expression (trailing + sign) so
#
R continues reading lines of code until the expression is complete
> long.answer.name <- 500*factorial(long.variable.name) +
+ sqrt(really.long.variable.name)
# Writing two expressions on the same line requires a ;
> mean(x); var(x)