Converts a factor with numeric levels, or, a character vector with numeric values to a numeric vector using as.numeric_factor, or, as.numeric_character respectively. If an unnamed numeric vector is passed, it will be returned as a named numeric vector, if this vector is continuous, it will be returned discretised (by calling ts_discrete), the labels will be rounded to `signif(x, digits = 4).

as.numeric_discrete(x, keepNA = FALSE, sortUnique = FALSE)

Arguments

x

A factor with levels that are numeric, or, a character vector representing numbers.

keepNA

Keep NA values (TRUE), or remove them (default = FALSE)

sortUnique

Should the unique character/factor level values be sorted? (default = FALSE)

Value

A named numeric vector with original factor levels / character values / numeric values as names.

Examples


# Continuous
i <- runif(10,0,9)
as.numeric_discrete(i)
#>  0.7268   7.509   5.407   1.415 0.06659   4.198    4.48   2.608   6.596   6.953 
#>       1       5       4       1       1       3       3       2       5       5 

# Integer
as.numeric_discrete(round(i))
#> 1 8 5 1 0 4 4 3 7 7 
#> 1 8 5 1 0 4 4 3 7 7 

# Factor with NAs
f <- factor(c(round(runif(9,0,9)),NA))
as.numeric_discrete(f)
#> 8 2 0 3 4 2 4 1 3 
#> 8 2 0 3 4 2 4 1 3 
as.numeric_discrete(f, keepNA = FALSE)
#> 8 2 0 3 4 2 4 1 3 
#> 8 2 0 3 4 2 4 1 3 

# Character vector
c <- c("Thank","you", "for", "the flowers")
as.numeric_discrete(c)
#>       Thank         you         for the flowers 
#>           1           2           3           4 
as.numeric_discrete(c, sortUnique = TRUE)
#>       Thank         you         for the flowers 
#>           1           4           2           3 

c <- c("Thank","you", "for", "the", "flowers")
as.numeric_discrete(c)
#>   Thank     you     for     the flowers 
#>       1       2       3       4       5 
as.numeric_discrete(c, sortUnique = TRUE)
#>   Thank     you     for     the flowers 
#>       1       5       3       4       2