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 5. Working with Basic Objects

In the previous chapters, you learned how to create several basic types of objects, including atomic vectors, lists, and data frames to store data. You learned how to create functions to store logic. Given these building blocks of R script, you learned about different types of expressions to control the flow of logic involving basic objects. Now, we are getting familiar with the basic grammar and syntax of the R programming language. It's time to build a vocabulary of R using built-in functions to work with basic objects.

The real power of R lies in the enormous amount of functions it provides. Getting to know a variety of basic functions is extremely useful, and it will save you time and boost your productivity.

Although R is mainly a statistical computing environment, many basic functions are not related to any statistics but to more fundamental tasks such as inspecting the environment, converting texts to numbers, and performing logical operations.

In...

Using object functions


In the previous chapter, you learned about some functions that work with the environment and packages. In this section, we will get to know some basic functions that deal with objects in general. More specifically, I will introduce you to more functions to access the type and dimensions of a data object. You will get an impression of how these concepts can be combined and how they work together.

Testing object types

Although everything in R is an object, objects have different types.

Suppose the object we are dealing with is user-defined. We will create a function that behaves in different ways according to the type of the input object. For example, we need to create a function named take_it that returns the first element if the input object as an atomic vector (for example, numeric vector, character vector, or logical vector), but returns a user-defined element if the input object is a list of data and index.

For example, if the input is a numeric vector such as c(1,...

Using logical functions


A logical vector only takes TRUE or FALSE and is mostly used to filter data. In practice, it is common to create joint conditions by multiple logical vectors where a number of logical operators and functions may involve.

Logical operators

Like many other programming languages, R enables a few operators to do basic logical calculations. The following table demonstrates what they do:

Symbol

Description

Example

Result

&

Vectorized AND

c(T, T) & c(T, F)

c(TRUE, FALSE)

|

Vectorized OR

c(T, T) | c(T, F)

c(TRUE, TRUE)

&&

Univariate AND

c(T, T) && c(F, T)

FALSE

||

Univariate OR

c(T, T) || c(F, T)

TRUE

!

Vectorized NOT

!c(T, F)

c(FALSE, TRUE)

%in%

Vectorized IN

c(1, 2) %in% c(1, 3, 4, 5)

c(TRUE, FALSE)

Note that in an if expression, && and || are often used to perform logical calculations that are only needed to yield a single-element logical vector. However, the potential risk of using && is that if it is made...

Using math functions


Mathematical functions are an essential part in all computing environments. R provides several groups of basic math functions.

Basic functions

The basic functions include square root, and exponential and logarithm functions as the following table shows:

Note that sqrt() only works with real numbers. If a negative number is supplied, NaN will be produced:

sqrt(-1)
## Warning in sqrt(-1): NaNs produced
## [1] NaN 

In R, numeric values can be finite, infinite (Inf and -Inf), and NaN values. The following code will produce infinite values.

First, produce a positively infinite value:

1 / 0
## [1] Inf 

Then, produce a negatively infinite value:

log(0)
## [1] -Inf 

There are several test functions to check whether a numeric value is finite, infinite, or NaN:

is.finite(1 / 0)
## [1] FALSE
is.infinite(log(0))
## [1] TRUE 

Using is.infinite(), how can we check whether a numeric value is -Inf? Inequality still works with infinite values...

Applying numeric methods


In the previous sections, you learned about a number of functions that range from inspecting data structures to math and logical operations. These functions are fundamental to solving problems such as root finding and doing calculus. As a computing environment, R already implements various tools of good performance so that users do not have to reinvent the wheel. In the following sections, you will learn the built-in functions designed for root finding and calculus.

Root finding

Root finding is a commonly encountered task. Suppose we want to find the roots of the following equation:

x2 + x - 2= 0

To manually find the roots, we can transform the preceding equation in product terms:

(x+2)(x-1)= 0

Therefore, the roots of the equation are x1= -2 and x2= 1.

In R, polyroot() can find roots of a polynomial equation in the form of:

For the preceding problem, we need to specify the polynomial coefficient vector from zero order to the term of the highest order present in the equation...

Using statistical functions


R is highly productive in doing statistical computing and modeling since it provides a good variety of functions ranging from random sampling to statistical testing. The functions in the same category share a common interface. In this section, I will demonstrate a number of examples so that you can draw inferences about the usage of other similar functions.

Sampling from a vector

In statistics, the study of a population often begins with a random sample of it. The sample() function is designed for drawing a random sample from a given vector or list. In default, sample() draws a sample without replacement. For example, the following code draws a sample of five from a numeric vector without replacement:

sample(1:6, size = 5)
## [1] 2 6 3 1 4 

With replace = TRUE, the sampling is done with replacement:

sample(1:6, size = 5, replace = TRUE)
## [1] 3 5 3 4 2 

Although sample() is often used to draw samples from a numeric vector, it also works with other...

Using apply-family functions


Previously, we talked about using a for loop to repeat evaluating an expression with an iterator on a vector or list. In practice, however, the for loop is almost the last choice because an alternative way is much cleaner and easier to write and read when each iteration is independent of each other.

For example, the following code uses for to create a list of three independent, normally distributed random vectors whose length is specified by vector len:

len <- c(3, 4, 5)
# first, create a list in the environment.
x <- list()
# then use `for` to generate the random vector for each length
for (i in 1:3) {
  x[[i]] <- rnorm(len[i])
}
x
## [[1]]
## [1] 1.4572245 0.1434679 -0.4228897
##
## [[2]]
## [1] -1.4202269 -0.7162066 -1.6006179 -1.2985130
##
## [[3]]
## [1] -0.6318412  1.6784430  0.1155478  0.2905479 -0.7363817 

The preceding example is simple, but the code is quite redundant...

Summary


In this chapter, you learned how to work basic objects by demonstrating the use of built-in functions. They are the vocabulary of R in practice. You learned some basic functions to test and get object types and to access and reshape data dimensions. You learned about a number of logical operators and functions to filter data.

To work with numeric data structures, you learned basic math functions, built-in numeric methods to find roots and do calculus, and some statistical functions to perform random sampling and make summaries of data. You also understood the apply-family functions that make it easier to iterate and collect results.

Another important category of data is string, which is represented by character vectors. In the next chapter, you will learn string-manipulation techniques to facilitate text 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 $15.99/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