Description Usage Arguments Value Functions Examples
as.Numeric
is similar to as.numeric
except that 1)
it results in an error for character strings for which as.numeric would
send a warning, 2) keeps integer, Date and POSIXt objects as they are (i.e.
does not convert them to double), 3) coerces logicals to integer, not double,
4) keeps 'dim' and 'dimnames' attributes if requested, and 5) always copies
the original object, even if no actual coercion occurs. as.Numeric_
returns the original object if possible and does not alter the shape of
multidimensional inputs.
1 2 3 | as.Numeric(x, keep_dim = FALSE)
as.Numeric_(x)
|
x |
the object to coerce |
keep_dim |
logical value whether |
as.Numeric
returns the original object (at the same memory
address) if it is numeric (that is, is.numeric(x) returns TRUE) or inherits
"Date" or "POSIXt" classes. Otherwise, it returns a double vector if
as.numeric
is successful and stops with an error if
as.numeric
results in a warning or error.
as.Numeric_
: Modify by reference
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | # if 'x' is double, as.Numeric() simply returns it, just like as.numeric()
x <- rnorm(10)
stopifnot(identical(as.numeric(x), as.Numeric(x)))
# if 'x' is integer, as.Numeric() simply returns it,
# but as.numeric() converts to double
x <- 1:10
stopifnot(identical(x, as.Numeric(x)))
stopifnot(all.equal(as.numeric(x), as.Numeric(x))) # not fully identical!
# if 'x' is Date or POSIXt, as.Numeric() simply returns it
x1 <- as.Date("2013-03-14")
x2 <- as.POSIXlt(x1)
stopifnot(identical(x1, as.Numeric(x1)))
stopifnot(identical(x2, as.Numeric(x2)))
# if 'x' contains only numeric-like characters (or NAs),
# as.Numeric() returns the same as as.numeric()
x <- c(NA, as.character(1:10))
stopifnot(identical(as.numeric(x), as.Numeric(x)))
# if 'x' contains any non-numeric characters (e.g. letters),
# as.Numeric() returns an error
x <- c("a", as.character(1:10))
x_num <- try(as.Numeric(x), silent = TRUE)
stopifnot(inherits(x_num, "try-error"))
# if 'x' is a matrix or array, as.Numeric() converts it to a vector by
# default, just like as.numeric()
( y <- x <- matrix(rnorm(10), 5, 2) )
( x_num <- as.Numeric(x) )
stopifnot(is.null(attr(x_num, "dim")))
# however, you can ask to keep the original shape
( x_num2 <- as.Numeric(x, TRUE) )
# if you use as.Numeric_() instead, it keeps the shape
( x_num3 <- as.Numeric_(x) )
stopifnot(identical(x_num3, x))
# note that since 'x' is numeric, no coercion is needed, so
# so as.Numeric_() does not create a copy, but as.Numeric() does
address(x)
address(x_num2)
address(x_num3)
stopifnot(identical(address(x), address(x_num3)))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.