num_as_char: Convert a number into a character sequence.

View source: R/num_util_fun.R

num_as_charR Documentation

Convert a number into a character sequence.

Description

num_as_char converts a number into a character sequence (of a specific length).

Usage

num_as_char(x, n_pre_dec = 2, n_dec = 2, sym = "0", sep = ".")

Arguments

x

Number(s) to convert (required, accepts numeric vectors).

n_pre_dec

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.

n_dec

Number of digits after the decimal separator. Default: n_dec = 2.

sym

Symbol to add to front or back. Default: sym = 0. Using sym = " " or sym = "_" can make sense, digits other than "0" do not.

sep

Decimal separator to use. Default: sep = ".".

Details

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.

See Also

Other numeric functions: base2dec(), base_digits, dec2base(), is_equal(), is_wholenumber(), num_as_ordinal(), num_equal()

Other utility functions: base2dec(), base_digits, dec2base(), is_equal(), is_vect(), is_wholenumber(), num_as_ordinal(), num_equal()

Examples

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")


ds4psy documentation built on Sept. 15, 2023, 9:08 a.m.