as.numeric()
get_help()
docs
The as.numeric()
function comes with R and is part of the Base R {base}
package.
We use this function to coerce a value or variable to be a numeric, i.e. change the variable’s type into a numeric type.
Not all values can be changed to numeric, and this function will return NA
if the value could not be coerced.
as.numeric(value to coerce into numeric type)
# Convert the string "10" to the number 10
as.numeric("10")
## [1] 10
# This example will return NA since there is no natural way to coerce the argument into a numeric
# It will also reveal a warning message telling you the coercion wasn't possible
as.numeric("you can't make strings into numbers")
## Warning: NAs introduced by coercion
## [1] NA
# The logical `TRUE` turns into 1 when coerced to be a number.
# This is consistent across all programming languages that allow coersion.
as.numeric(TRUE)
## [1] 1
# The logical `FALSE` turns into 0 when coerced to be a number.
# This is consistent across all programming languages that allow coersion.
as.numeric(FALSE)
## [1] 0
# Example of coercing a column in a tibble to be numeric.
# This will only work if the column values are allowed to be numbers
# First, create and show a tibble to use for the example:
<- tibble::tibble(
example_tib column1 = c("1", "2", "3", "4"),
column2 = c("a", "b", "c", "d")
) example_tib
## # A tibble: 4 × 2
## column1 column2
## <chr> <chr>
## 1 1 a
## 2 2 b
## 3 3 c
## 4 4 d
# We can successfully coerce column1, but column2 will becomes NAs
$column1 <- as.numeric(example_tib$column1)
example_tib$column2 <- as.numeric(example_tib$column2) example_tib
## Warning: NAs introduced by coercion
# Show data after coersion:
example_tib
## # A tibble: 4 × 2
## column1 column2
## <dbl> <dbl>
## 1 1 NA
## 2 2 NA
## 3 3 NA
## 4 4 NA
# Or, we can coerce (or attempt coercion) with dplyr::mutate()
%>%
example_tib ::mutate(column1 = as.numeric(column1),
dplyrcolumn2 = as.numeric(column2))
## # A tibble: 4 × 2
## column1 column2
## <dbl> <dbl>
## 1 1 NA
## 2 2 NA
## 3 3 NA
## 4 4 NA