2 minute read

Recursive Functions�����������������������������������������������������������������������������������������������������

Chapter 8 ■ More r prograMMing

The | and || are logical “or” operators while & and && are logical “and” operators. The difference between | and || or & and && are how they deal with vectors. The one-character version will apply the operator element-wise and create a vector while the two-character version will only look at the first value in vectors.

Advertisement

TRUE | FALSE ## [1] TRUE FALSE | FALSE ## [1] FALSE TRUE || FALSE ## [1] TRUE FALSE || FALSE ## [1] FALSE x <- c(TRUE, FALSE, TRUE, FALSE) y <- c(TRUE, TRUE, FALSE, FALSE)

x | y ## [1] TRUE TRUE TRUE FALSE x || y ## [1] TRUE x & y ## [1] TRUE FALSE FALSE FALSE x && y ## [1] TRUE

We typically use the two-character version in control structures like if—since these do not operate on vectors in any case—while we use the one-character version when we need to compute with Boolean arithmetic, when we want our expressions to work as vectorized expressions.

Incidentally, all the arithmetic operators work like the | and & operators when operating on more than one value, i.e., they operate element-wise on vectors. We saw that in Chapter 1 when we talked about vector expressions.

Basic Data Types

There are a few basic types in R: numeric, integer, complex, logical, and character.

The Numeric Type

The numeric type is what you get any time you write a number into R. You can test if an object is numeric using the is.numeric function or by getting the class object.

is.numeric(2) ## [1] TRUE class(2) ## [1] "numeric"

207

Chapter 8 ■ More r prograMMing

The Integer Type

The integer type is used for, well, integers. Surprisingly, the 2 is not an integer in R. It is a numeric type which is the larger type that contains all floating-point numbers as well as integers. To get an integer you have to make the value explicitly an integer, and you can do that using the function as.integer or writing L after the literal.

is.integer(2) ## [1] FALSE is.integer(2L) ## [1] TRUE x <- as.integer(2) is.integer(x) ## [1] TRUE class(x) ## [1] "integer"

If you translate a non-integer into an integer, you just get the integer part.

as.integer(3.2) ## [1] 3 as.integer(9.9) ## [1] 9

The Complex Type

If you ever find that you need to work with complex numbers, R has those as well. You construct them by adding an imaginary number—a number followed by i—to any number or explicitly using the function as. complex. The imaginary number can be zero, 0i, which creates a complex number that only has a non-zero real part.

1 + 0i ## [1] 1+0i is.complex(1 + 0i) ## [1] TRUE class(1 + 0i) ## [1] "complex" sqrt(as.complex(-1)) ## [1] 0+1i

The Logical Type

Logical values are what you get if you explicitly type in TRUE or FALSE, but it is also what you get if you make, for example, a comparison.

x <- 5 > 4 x ## [1] TRUE class(x) ## [1] "logical"

208

This article is from: