R語言格式化數字和字符串format函數


數字和字符串可以使用 format()函數的格式化為特定樣式。

語法

format()函數的基本語法是:

format(x, digits, nsmall,scientific,width,justify = c("left", "right", "centre", "none"))     

以下是所使用的參數的說明:

  • x - 為向量輸入
  • digits - 是顯示總位數
  • nsmall - 是最小位數的小數點右邊
  • scientific - 設置為TRUE,則顯示科學記數法
  • width - 指示要通過填充空白在開始時顯示的最小寬度
  • justify - 是字符串顯示在左邊,右邊或中心

示例

# Total number of digits displayed. Last digit rounded off.
result <- format(23.123456789, digits = 9)
print(result)

# Display numbers in scientific notation.
result <- format(c(6, 13.14521), scientific = TRUE)
print(result)

# The minimum number of digits to the right of the decimal point.
result <- format(23.47, nsmall = 5)
print(result)

# Format treats everything as a string.
result <- format(6)
print(result)

# Numbers are padded with blank in the beginning for width.
result <- format(13.7, width = 6)
print(result)

# Left justify strings.
result <- format("Hello",width = 8, justify = "l")
print(result)

# Justfy string with center.
result <- format("Hello",width = 8, justify = "c")
print(result)

當我們上面的代碼執行時,它產生以下結果:

[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] "  13.7"
[1] "Hello   "
[1] " Hello  "


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM