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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。