cast: Casting Types

Description Usage Arguments Details Value See Also Examples

View source: R/cast.R

Description

Convert a data object from one type to another.

Usage

1
cast(type, x)

Arguments

type

an object with the destination type.

x

the source object.

Details

The cast function converts a data object from one type to another. Its behavior is similar to that of the base type conversion functions (as.character, as.integer, etc.), but it allows for a dynamically-determined type.

The type argument can be any object with the desired destination type such that schema(type) is well-defined. The source x object must likewise be such that schema(x) is well defined.

For the conversion to succeed, the number of components of schema(x) must match that of type(x). Even so, if a value in the source object cannot be represented in the destination type, then the cast operation will raise a warning or error.

When casting to a record type, the names in the source object must either be NULL or match the destination type.

Value

The data object x converted to the destination type.

See Also

schema.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# conversion to basic types
cast(integer(), c(TRUE, FALSE, NA))
cast(character(), c(TRUE, FALSE, NA))
cast(integer(), c(1.2, -99, NaN))

# conversion to factor
f <- factor(c(), levels = letters)
cast(f, c("a", "e", "i", "o", "u"))
cast(f, factor(c("a", "e", "i", "o", "u")))
## Not run: cast(f, "A") # invalid level; raises a warning

# conversion to record
r <- record(int = integer(), lgl = logical(), chr = character())
x <- record(a = 1.3, b = "TRUE", c = 3.14)

## Not run: cast(r, x) # fails, names don't match
cast(r, unname(x))   # succeed, source names are NULL
cast(unname(r), x)   # succeeds, destination names are NULL
names(x) <- names(r)
cast(r, x)           # succeeds, names match

#  conversion from POSIXct 'America/New_Nork' to 'America/Los_Angeles'
t <- as.POSIXct("0000-01-01 00:00:00", tz = "America/Los_Angeles")[0]
x <- as.POSIXct("2000-10-26 10:00:00", tz = "America/New_York")
cast(t, x)

patperry/r-frame documentation built on May 6, 2019, 8:34 p.m.