Reputation: 99478
as.matrix
will convert a data frame to a matrix. as.data.frame
will do the opposite conversion.
ts
will convert a vector, matrix or data frame to a time series object.
So I wonder why as.
appear in some functions' names, and not in the others? Thanks!
Upvotes: 0
Views: 92
Reputation: 3243
Following Tim's comment request...
Generally speaking
matrix
and ts
(like other function with class-like-name
) are
used when you create an object from scratch (eg a data.frame
from a set of vector, a matrix
from a vector specifying dims).as.matrix
and as.ts
(like other function like as.classname
) are
used to coerce an object of a given class to classname
.matrix
and as.matrix
fits the general rule quite well.
matrix
is tipically efficient in creating an object from
scratch. You can see that after a few manipulation it call low
level code (via .Internal
) to provide the correct data
structure.
> matrix
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{
if (is.object(data) || !is.atomic(data))
data <- as.vector(data)
.Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow), missing(ncol)))
}
as.*
function aim (eg as.matrix
's one) is totally different because they have to cope
with different/complex data structures, all to be coerced to that considered.
Therefore are somewhat more high-level function (pure R mainly)
> as.matrix
function (x, ...)
UseMethod("as.matrix")
<bytecode: 0x3a5a2f0>
<environment: namespace:base>
which objects can be converted to matrix?
> methods(as.matrix)
[1] as.matrix.data.frame as.matrix.default
[3] as.matrix.dist* as.matrix.ftable*
[5] as.matrix.noquote as.matrix.POSIXlt
[7] as.matrix.raster*
Non-visible functions are asterisked
try from the console
as.matrix.data.frame
as.matrix.ftable
getAnywhere(as.matrix.ftable)
HTH :)
Upvotes: 3
Reputation: 263411
Naming a function as.new_class_name
is part of the S3 function dispatch mechanism. If you want to define a new class and a function to provide coercion to that class, then you make an as.new_class_name
function and register it using setClass
. see the examples at:
?setAs
?setClass
The interpreter will then be able to properly dispatch to as.new_class_name
(assuming you have defined it) when it encounters such a call.
Upvotes: 2