R语言 数字和字符串格式化 – format()函数

R语言 数字和字符串格式化 – format()函数

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

语法: format(x, digits, nsmall, scientific, width, justify = c("left", "right", "center", "none")

参数

  • x: 是输入的向量。
  • digits: 是显示的总位数。
  • nsmall: 是小数点右边的最小数字。
  • scientific: 设置为TRUE,显示科学符号。
  • width: 表示通过在开头填充空白来显示的最小宽度。
  • justify: 是指将字符串显示在左边、右边或中间。

R中的字符串格式化

例子: 在这个例子中,我们将使用format()方法在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)

输出

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

R语言 数字格式化

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

例1 :

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程