Related Articles

Related Articles

Formatting Numbers and Strings in R Programming – format() Function
  • Last Updated : 29 Jun, 2020

format() function in R Language is used to format strings and numbers in a specified style.

Syntax: format(x, digits, nsmall, scientific, width, justify = c(“left”, “right”, “center”, “none”))

Parameters:
x: is the vector input.
digits: is the total number of digits displayed.
nsmall: is the minimum number of digits to the right of the decimal point.
scientific: is set to TRUE to display scientific notation.
width: indicates the minimum width to be displayed by padding blanks in the beginning.
justify: is the display of the string to left, right, or center.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# format function
  
# Calling the format() function over
# different arguments
  
# Rounding off the specified digits
# into 4 digits
result1 <- format(12.3456789, digits = 4
result2 <- format(12.3456789, digits = 6
print(result1) 
print(result2) 
  
# Getting the specified minimum number of digits  
# to the right of the decimal point. 
result3 <- format(12.3456789, nsmall = 2
result4 <- format(12.3456789, nsmall = 7
print(result3) 
print(result4) 

chevron_right


Output:



[1] "12.35"
[1] "12.3457"
[1] "12.34568"
[1] "12.3456789"

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# format function
  
# Calling the format() function over
# different arguments
  
# Getting the number in the string form
result1 <- format(1234
result2 <- format(12.3456789
print(result1) 
print(result2) 
    
# Display numbers in scientific notation
result3 <- format(12.3456789, scientific = TRUE) 
result4 <- format(12.3456789, scientific = FALSE) 
print(result3) 
print(result4) 

chevron_right


Output:

[1] "1234"
[1] "12.34568"
[1] "1.234568e+01"
[1] "12.34568"

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# format function
  
# Calling the format() function over
# different arguments
    
# Adding any number of spaces 
# in the beginning
result1 <- format(12.34, width = 2
result2 <- format(12.34, width = 6
print(result1) 
print(result2) 
    
# Placing string in the left side
result3 <- format("GFG", width = 8,  justify = "l"
  
# Placing string in the center
result4 <- format("GFG", width = 8,  justify = "c"
  
# Placing string in the right
result5 <- format("GFG", width = 8,  justify = "r"
  
# Getting the different string placement
print(result3) 
print(result4) 
print(result5) 

chevron_right


Output:

[1] "12.34"
[1] " 12.34"
[1] "GFG     "
[1] "  GFG   "
[1] "     GFG"



My Personal Notes arrow_drop_up
Recommended Articles
Page :