Reader small image

You're reading from  Learning R Programming

Product typeBook
Published inOct 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785889776
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Kun Ren
Kun Ren
author image
Kun Ren

Kun Ren has used R for nearly 4 years in quantitative trading, along with C++ and C#, and he has worked very intensively (more than 8-10 hours every day) on useful R packages that the community does not offer yet. He contributes to packages developed by other authors and reports issues to make things work better. He is also a frequent speaker at R conferences in China and has given multiple talks. Kun also has a great social media presence. Additionally, he has substantially contributed to various projects, which is evident from his GitHub account: https://github.com/renkun-ken https://cn.linkedin.com/in/kun-ren-76027530 http://renkun.me/ http://renkun.me/formattable/ http://renkun.me/pipeR/ http://renkun.me/rlist/
Read more about Kun Ren

Right arrow

Chapter 4. Basic Expressions

Expressions are the building blocks of a function. R has a very clear syntax that suggests that an expression is either a symbol or a function call.

Although everything we do is in essence implemented by functions, R gives some functions a special syntax so that it is more friendly to write readable R code.

In the next few sections, we will see the following fundamental expressions that are given a special syntax:

  • Assignment expressions

  • Conditional expressions

  • Loop expressions

Assignment expressions


Assignment may be one of the most fundamental expressions in all programming languages. What it does is assign or bind a value to a symbol so that we can refer to the value by that symbol later.

Despite the similarity, R adopts the <- operator to perform assignment. This is a bit different from many other languages using = although this is also allowed in R:

x <- 1 
y <- c(1, 2, 3) 
z <- list(x, y) 

We don't have to declare the symbol and its type before assigning a value to it. If a symbol does not exist in the environment, the assignment will create that symbol. If a symbol already exists, the assignment will not end up in conflict, but will rebind the new value to that symbol.

Alternative assignment operators

There are some alternate yet equivalent operators we can use. Compared to x <- f(z), which binds the value of f(z) to symbol x, we can also use -> to perform assignment in the opposite direction:

2 -> x1 

We can even chain...

Conditional expressions


It is common that the logic of a program is not perfectly sequential but contains several branches dependent on certain conditions. Therefore, one of the most basic constructs of a typical programming language is its conditional expressions. In R, if can be used to branch the logic flow by logical conditions.

Using if as a statement

Like many other programming languages, the if expression works with a logical condition. In R, a logical condition is represented by an expression producing a single-element logical vector. For example, we can write a simple function check_positive that returns 1 if a positive number is provided and nothing otherwise:

check_positive <- function(x) { 
  if (x > 0) { 
    return(1) 
  } 
} 

In the preceding function, x > 0 is the condition to check. If the condition is satisfied, then the function returns 1. Let's verify the function with various inputs:

check_positive(1)
## [1] 1
check_positive(0...

Loop expressions


Loop (or iteration) evaluates an expression repeatedly by either iterating over a vector (for) or checking whether a condition is violated (while).

Such language constructs largely reduce the redundancy of the code if the same task is run over and over again each time with some changes in input.

Using the for loop

The for loop evaluates an expression by iterating over a given vector or list. The syntax of a for loop is as follows:

for (var in vector) { 
  expr 
} 

Then, expr will be evaluated iteratively, with var taking the value of each element of vector in turn. If vector has n elements, then the preceding loop is equivalent to evaluating:

var <- vector[[1]] 
expr 
var <- vector[[2]] 
expr 
... 
var <- vector[[n]] 
expr 

For example, we can create a loop to iterate over 1:3 with iterator variable i. In each iteration, we will show text on the screen to indicate the value of i:

for (i in 1:3) {
cat("The value of...

Summary


In this chapter, you learned the syntax of assignment, conditional expressions, and loops. In the section on assignment, you got to know the naming rules of variables and how to walk around. In the section on conditional expressions, you learned how to use the if statement as either a statement or an expression, and how ifelse()is distinct from if when dealing with vectors. In the section on loops, you learned about the similarities and differences between for loops and while loops. Now, we are equipped with the basic expressions to control the logic flow of an R program.

In the next chapter, you will use what you learned in the previous chapters and see what you can do with the basic objects representing data and basic expressions representing our logic. You will learn about basic functions in various categories as the building blocks of data transformation and statistical analysis.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning R Programming
Published in: Oct 2016Publisher: PacktISBN-13: 9781785889776
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
Kun Ren

Kun Ren has used R for nearly 4 years in quantitative trading, along with C++ and C#, and he has worked very intensively (more than 8-10 hours every day) on useful R packages that the community does not offer yet. He contributes to packages developed by other authors and reports issues to make things work better. He is also a frequent speaker at R conferences in China and has given multiple talks. Kun also has a great social media presence. Additionally, he has substantially contributed to various projects, which is evident from his GitHub account: https://github.com/renkun-ken https://cn.linkedin.com/in/kun-ren-76027530 http://renkun.me/ http://renkun.me/formattable/ http://renkun.me/pipeR/ http://renkun.me/rlist/
Read more about Kun Ren