Last chance! 50% off unlimited learning
Sale ends in
num_as_char
converts a number into a character sequence
(of a specific length).
num_as_char(x, n_pre_dec = 2, n_dec = 2, sym = "0", sep = ".")
Number(s) to convert (required, accepts numeric vectors).
Number of digits before the decimal separator.
Default: n_pre_dec = 2
.
This value is used to add zeros to the front of numbers.
If the number of meaningful digits prior to decimal separator is greater than
n_pre_dec
, this value is ignored.
Number of digits after the decimal separator.
Default: n_dec = 2
.
Symbol to add to front or back.
Default: sym = 0
.
Using sym = " "
or sym = "_"
can make sense,
digits other than "0"
do not.
Decimal separator to use.
Default: sep = "."
.
The arguments n_pre_dec
and n_dec
set a number of desired digits
before and after the decimal separator sep
.
num_as_char
tries to meet these digit numbers by adding zeros to the front
and end of x
. However, when n_pre_dec
is lower than the
number of relevant (pre-decimal) digits, all relevant digits are shown.
n_pre_dec
also works for negative numbers, but
the minus symbol is not counted as a (pre-decimal) digit.
Caveat: Note that this function illustrates how numbers,
characters, for
loops, and paste()
can be combined
when writing functions. It is not written efficiently or well.
Other utility functions:
is_equal()
,
is_vector()
,
is_wholenumber()
,
num_as_ordinal()
,
num_equal()
# NOT RUN {
num_as_char(1)
num_as_char(10/3)
num_as_char(1000/6)
# rounding down:
num_as_char((1.3333), n_pre_dec = 0, n_dec = 0)
num_as_char((1.3333), n_pre_dec = 2, n_dec = 0)
num_as_char((1.3333), n_pre_dec = 2, n_dec = 1)
# rounding up:
num_as_char(1.6666, n_pre_dec = 1, n_dec = 0)
num_as_char(1.6666, n_pre_dec = 1, n_dec = 1)
num_as_char(1.6666, n_pre_dec = 2, n_dec = 2)
num_as_char(1.6666, n_pre_dec = 2, n_dec = 3)
# Note: If n_pre_dec is too small, actual number is kept:
num_as_char(11.33, n_pre_dec = 0, n_dec = 1)
num_as_char(11.66, n_pre_dec = 1, n_dec = 1)
# Note:
num_as_char(1, sep = ",")
num_as_char(2, sym = " ")
num_as_char(3, sym = " ", n_dec = 0)
# for vectors:
num_as_char(1:10/1, n_pre_dec = 1, n_dec = 1)
num_as_char(1:10/3, n_pre_dec = 2, n_dec = 2)
# for negative numbers (adding relevant pre-decimals):
mix <- c(10.33, -10.33, 10.66, -10.66)
num_as_char(mix, n_pre_dec = 1, n_dec = 1)
num_as_char(mix, n_pre_dec = 1, n_dec = 0)
# Beware of bad inputs:
num_as_char(4, sym = "8")
num_as_char(5, sym = "99")
# }
Run the code above in your browser using DataLab