R 语言中的 format() 函数用于以指定的样式格式化字符串和数字。
用法: format(x, digits, nsmall, scientific, width, justify = c(“left”, “right”, “center”, “none”))
参数:
x:是向量输入。
digits:是显示的总位数。
nsmall:是小数点右边的最小位数。
scientific:设置为 TRUE 以显示科学记数法。
width:表示通过在开头填充空白来显示的最小宽度。
justify:是向左、向右或居中显示字符串。
范例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"
范例3:
# 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)
输出:
[1] "12.34" [1] " 12.34" [1] "GFG " [1] " GFG " [1] " GFG"
相关用法
- R语言 as.Date()用法及代码示例
- R语言 noquote()用法及代码示例
- R语言 is.primitive()用法及代码示例
- R语言 paste()用法及代码示例
- R语言 strsplit()用法及代码示例
- R语言 seq.int()用法及代码示例
- R语言 optimize()用法及代码示例
- R语言 dunif()用法及代码示例
- R语言 lapply()用法及代码示例
- R语言 lgamma()用法及代码示例
- R语言 digamma()用法及代码示例
- R语言 trigamma()用法及代码示例
- R语言 args()用法及代码示例
注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 Formatting Numbers and Strings in R Programming – format() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。