What is the usage of the format function in R language?
In R language, the format() function is used to format numbers, dates, times, and other data into specific string forms. Its syntax is as follows:
The function format(x, …) is used to format the object x, which can be a number, a date, or a time. The optional parameters in … are used to specify specific formatting settings.
Here are some common usage examples:
- Format numbers:
x <- 12345.6789
x_formatted <- format(x, nsmall = 2) # 保留2位小数
print(x_formatted) # 输出:12,345.68
- Format date:
date <- as.Date("2021-09-01")
date_formatted <- format(date, "%Y年%m月%d日") # 格式化为"年-月-日"形式
print(date_formatted) # 输出:2021年09月01日
- Format the time:
time <- as.POSIXct("12:34:56", format = "%H:%M:%S")
time_formatted <- format(time, "%H时%M分%S秒") # 格式化为"时:分:秒"形式
print(time_formatted) # 输出:12时34分56秒
These are just some common usage examples of the format() function, in reality it can be customized for more complex formatting as needed. You can find more detailed information in R’s help documentation or other resources.