📜  在 R 编程中格式化数字和字符串 - format()函数

📅  最后修改于: 2022-05-13 01:54:21.674000             🧑  作者: Mango

在 R 编程中格式化数字和字符串 - format()函数

R 编程语言中的format()函数用于以指定的样式格式化字符串和数字。

R中的字符串格式

示例:在此示例中,我们将使用 format() 方法在 R 编程中处理字符串格式化。

R
# Placing string in the left side
result1 <- format("GFG", width = 8,  justify = "l")
 
# Placing string in the center
result2 <- format("GFG", width = 8,  justify = "c")
 
# Placing string in the right
result3 <- format("GFG", width = 8,  justify = "r")
 
# Getting the different string placement
print(result1)
print(result2)
print(result3)


R
# 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)


R
# 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)


输出:

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

R中的数字格式

在这里,我们将使用 format() 方法在 R 编程中进行数字格式化。

示例 1:

R

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

输出:

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

示例 2:

R

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

输出:

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