RBasic 101
Kyle Chung
2016-05-13
Chapter 1 Prologue
The materials of this book target at new users or users not very familiar with R. Before you start to read this book, take a look at the following examples to test your familiarity with the R language.
1.1 Thought Experiments
1.1.1 First Trial
A <- 1 + 1
(B <- 1 + 1)
## [1] 2
identical(A, B)
## [1] TRUE
Now you know that adding parenthesis around an expression will force R to print the result of it. But why? If you immediately type ?"("
to search for a possible anwser, you are probably not new to the R language. And if you can further read the document and get yourself understood, you are not the targeted reader of this book.
1.1.2 Second Trial
a_vec <- 1:2
names(a_vec)
## NULL
names(a_vec) <- c("foo", "bar")
names(a_vec)
## [1] "foo" "bar"
The function names
is used to return the names of the object given, if any. In the third line we also use names
to rename the object. Now you know that we can use such tech to rename an object. But how is it possible to asign a value to the returned value of a function?
Should you really think it is okay to do so, then think about the following codes:
xf <- function(x) x
xf(1) <- 2
## Error in xf(1) <- 2: target of assignment expands to non-language object
Oops! Acutally you can’t do that. Asign a value to the returned value of a function causes an error. But names(a_vec) <- c("foo", "bar")
does work, right? If you do understand the reason why it actually works, you are not the targeted reader of this book.
1.1.3 Third Trial
`+`(1, 2)
## [1] 3
You may never see this coming before, or you just don’t code in such style, but you do understand this is a function call to the add function, in a functional way. That say, you are completely comfortable about the following codes:
for ( op in c(`+`, `-`, `*`, `/`) )
print(op(10, 2))
## [1] 12
## [1] 8
## [1] 20
## [1] 5
Then you are not the targeted reader of this book.
1.2 Welcome to the R Language
If all the above examples bother you nothing, you are not the targeted reader of this book since you are quite familiar with the R language and you do know how to dive depper on your own. But if some or all of the above examples make you confused or starting googling, you can learn from this book.
This book is NOT a HOW-TO cookbook to teach you how to write in the R language. A HOW-TO cookbook will let you know, in the R language, how to force print an expression, or rename an object. This book is NOT a HOW-TO cookbook. Yes we can use (
to force print an expression. But why? Yes we can use names
to rename an object. But why? This book is to teach you WHY we write R in this or that way. Consequently you are not just coding in R, you are also thinking in R. And that’s where the R language starts to shine.