如何在dplyr中将数字格式化为无小数位且向上取整的货币格式
Got it, let's tackle this step by step. You need two core actions here: rounding up to the nearest whole dollar and then formatting that value as a currency string with a $ sign and no decimal places. Here are two straightforward ways to do this using dplyr verbs:
Method 1: Using the scales Package (Simplest Approach)
The scales package has a built-in dollar() function that handles currency formatting perfectly. First, make sure you have the package installed if you haven't already:
install.packages("scales")
Then use dplyr::mutate() to modify your column (or create a new formatted column):
library(dplyr) library(scales) # Replace 'your_data' with your actual data frame name your_data <- your_data %>% mutate( # Option 1: Create a new formatted column (keeps original numeric data intact) Quote_Dollars_Formatted = dollar(ceiling(Quote_Dollars), decimal_places = 0), # Option 2: Overwrite the original column (note: changes column type from numeric to character) # Quote_Dollars = dollar(ceiling(Quote_Dollars), decimal_places = 0) )
Breakdown:
ceiling(Quote_Dollars): This rounds every value up to the nearest whole dollar (e.g., 703822.5 → 703823, 1000.5 → 1001).dollar(..., decimal_places = 0): Adds the$symbol, includes thousands separators, and hides any decimal places since we setdecimal_placesto 0.
Method 2: No Extra Packages (Base R + dplyr)
If you prefer not to install another package, you can combine base R's formatC() with stringr::str_c() (or base paste0()) to achieve the same result:
library(dplyr) library(stringr) # Or use base R's paste0() if you don't have stringr installed your_data <- your_data %>% mutate( Quote_Dollars_Formatted = str_c("$", formatC( ceiling(Quote_Dollars), format = "f", digits = 0, big.mark = "," )) )
Breakdown:
formatC(...): Formats the rounded integer with thousands separators and no decimals.str_c("$", ...): Prepends the$symbol to the formatted number string.
Example Output
For your sample value 703822.5, both methods will produce $703,823, and 1784781.3 becomes $1,784,782.
内容的提问来源于stack exchange,提问作者Jaskeil

