Data Concatenation and Coercion in R

Data concatenation and coercion are common operations in R.

Data Concatenation

The concatenate c() function is used to combine elements into a vector.

When elements are combined from different classes, the c() function coerces to a common type, which is the type of the returned value:

Paste Functions in R

The paste0() and the paste() functions are used to concatenate strings and vectors after converting to character.  Both are used extensively to define frequently used character strings, such as file paths, variable names, and strings generated by iterative functions.  The first function assumes the string elements to be combined have no separator (e.g. sep=””), while the second paste function requires a used defined separator:

Data Coercion in R

If elements of different modes are combined, R implicitly coerces all elements to the most informative class type.  As a rule, TRUE become 1 and FALSE becomes 0 when logical values are coerced to integers.  Some of the results below may seem non-sensical, but the examples clearly illustrate how data elements can be coerced.

Coercion is subject to testing and control.  The function is(x, “type”) is used to test if x is a certain type of class.  The function as(x, “type”) explicitly coerces data to a certain type.  

arrayis(x, "array")as(x, "array")
characteris(x, "character")as(x, "character")
complexis(x, "complex")as(x, "complex")
data.frameis(x, "data.frame")as(x, "data.frame")
doubleis(x, "double")as(x, "double")
environmentis(x, "environment")as(x, "environment")
factoris(x, "factor")as(x, "factor")
integeris(x, "interger")as(x, "interger")
listis(x, "list")as(x, "list")
logicalis(x, "logical")as(x, "logical")
matrixis(x, "matrix")as(x, "matrix")
NAis(x, "na")as(x, "na")
NaNis(x, "nan")is(x, "nan")
NULLis(x, "NULL")as(x, "NULL")
numericis(x, "numeric")as(x, "numeric")
singleis(x, "single")as(x, "single")
timeDateis(x, "timeDate")as(x, "timeDate")
timeSeriesis(x, "timeSeries")as(x, "timeSeries")
vectoris(x, "vector")as(x, "vector")

Back | Next

Leave a Reply

Your email address will not be published. Required fields are marked *