-
Try R
In this first chapter, we'll cover basic R expressions. We'll start simple, with numbers, strings, and true/false values. Then we'll show you how to store those values in variables, and how to pass them to functions. We'll show you how to get help on functions when you're stuck. Finally we'll load an R script in from a file.
Let's get started!
-
Expressions1.1
Type anything at the prompt, and R will evaluate it and print the answer.
Let's try some simple math. Type the below command.
[Or, if you prefer, click on the command and it will be typed into the console for you!]
Redo Complete> 1+1 [1] 2
There's your result,
2
. It's printed on the console right after your entry. -
Help1.5
help(functionname)
brings up help for the given function. Try displaying help for thesum
function:Redo Complete> help(sum) sum package:base R Documentation Sum of Vector Elements Description: 'sum' returns the sum of all the values present in its arguments. Usage: sum(..., na.rm = FALSE) ...
(Don't worry about that optional
na.rm
argument, we'll cover that later.) -
example(functionname)
brings up examples of usage for the given function. Try displaying examples for themin
function:Redo Complete> example(min) min> require(stats); require(graphics) min> min(5:1, pi) #-> one number [1] 1 min> pmin(5:1, pi) #-> 5 numbers [1] 3.141593 3.141593 3.000000 2.000000 1.000000 ...
-
Now try bringing up help for the
rep
function:Redo Complete> help(rep) rep package:base R Documentation Replicate Elements of Vectors and Lists Description: 'rep' replicates the values in 'x'. It is a generic function, and the (internal) default method is described here. ...
-
Files1.6
Typing commands each time you need them only works for short scripts, of course. R commands can also be written in plain text files (with a ".R" extension, by convention) for executing later. You can run them directly from the command line, or from within a running R instance.
We've stored a couple sample scripts for you. You can list the files in the current directory from within R, by calling the
list.files
function. Try it now: -
Chapter 1 Completed
Share your plunder:
You've reached the end of Chapter 1… where you discover a badge!
Excellent work! Now you know the basics of R expressions. You've learned how to create and access variables, and how to call functions. You've learned how to run pre-made scripts. And you've learned how to access R's help functionality when you need it.
Now it's time to learn about the features that make R really unique and useful - its data structures. Vectors are first; we'll talk about them in the next chapter!