Function to quick encode vector or columns to a specific format.
as_numeric()
: Encode columns to numeric usingas.numeric()
.as_integer()
: Encode columns to integer usingas.integer()
.as_logical()
: Encode columns to logical usingas.logical()
.as_character()
: Encode columns to character usingas.character()
.as_factor()
: Encode columns to factor usingas.factor()
.
Usage
as_numeric(.data, ..., .keep = "all", .pull = FALSE)
as_integer(.data, ..., .keep = "all", .pull = FALSE)
as_logical(.data, ..., .keep = "all", .pull = FALSE)
as_character(.data, ..., .keep = "all", .pull = FALSE)
as_factor(.data, ..., .keep = "all", .pull = FALSE)
Arguments
- .data
A data frame or a vector.
- ...
If
.data
is a data frame, then...
are the variable(s) to encode to a format.- .keep
Allows you to control which columns from
.data
are retained in the output."all"
(default) retains all variables."used"
keeps any variables used to make new variables.
- .pull
Allows you to pull out the last column of the output. It is useful in combination with
.keep = "used"
. In this case, a vector will be created with the used column.
Value
An object of the same class of .data
with the variables in
...
encoded to the specified format.
Author
Tiago Olivoto tiagoolivoto@gmail.com
Examples
# \donttest{
library(metan)
library(tibble)
#>
#> Attaching package: 'tibble'
#> The following objects are masked from 'package:metan':
#>
#> column_to_rownames, remove_rownames, rownames_to_column
df <-
tibble(y = rnorm(5),
x1 = c(1:5),
x2 = c(TRUE, TRUE, FALSE, FALSE, FALSE),
x3 = letters[1:5],
x4 = as.factor(x3))
df
#> # A tibble: 5 × 5
#> y x1 x2 x3 x4
#> <dbl> <int> <lgl> <chr> <fct>
#> 1 -1.11 1 TRUE a a
#> 2 0.658 2 TRUE b b
#> 3 -0.0433 3 FALSE c c
#> 4 0.628 4 FALSE d d
#> 5 -0.937 5 FALSE e e
# Convert y to integer
as_integer(df, y)
#> # A tibble: 5 × 5
#> y x1 x2 x3 x4
#> <int> <int> <lgl> <chr> <fct>
#> 1 -1 1 TRUE a a
#> 2 0 2 TRUE b b
#> 3 0 3 FALSE c c
#> 4 0 4 FALSE d d
#> 5 0 5 FALSE e e
as_integer(df$y)
#> [1] -1 0 0 0 0
# convert x3 to factor
as_factor(df, x3)
#> # A tibble: 5 × 5
#> y x1 x2 x3 x4
#> <dbl> <int> <lgl> <fct> <fct>
#> 1 -1.11 1 TRUE a a
#> 2 0.658 2 TRUE b b
#> 3 -0.0433 3 FALSE c c
#> 4 0.628 4 FALSE d d
#> 5 -0.937 5 FALSE e e
# Convert all columns to character
as_character(df, everything())
#> # A tibble: 5 × 5
#> y x1 x2 x3 x4
#> <chr> <chr> <chr> <chr> <chr>
#> 1 -1.10984201607485 1 TRUE a a
#> 2 0.657924261945017 2 TRUE b b
#> 3 -0.043296014259524 3 FALSE c c
#> 4 0.628389225007118 4 FALSE d d
#> 5 -0.936829212533565 5 FALSE e e
# Convert x2 to numeric and coerce to a vector
as_numeric(df, x2, .keep = "used", .pull = TRUE)
#> [1] 1 1 0 0 0
# }