简体   繁体   中英

R column data.frame from numeric to excel format ccurrency

How can I format a numeric column of data.frame to look like an excel style currency column. With the symbol '$' and ',' to separate thousands

From

data <- iris 
data$Sepal.Length <- data$Sepal.Length * 10**8
head(data[, c('Species', 'Sepal.Length')])
  Species Sepal.Length
1  setosa      5.1e+08
2  setosa      4.9e+08
3  setosa      4.7e+08
4  setosa      4.6e+08
5  setosa      5.0e+08

to this format

head(data[, c('Species', 'Sepal.Length')])
  Species Sepal.Length
1  setosa      $510,000,000  
2  setosa      $490,000,000 
3  setosa      $470,000,000 
4  setosa      $460,000,000 
5  setosa      $500,000,000


Base R:

data$Sepal.Length <- paste0("$", format(data$Sepal.Length, big.mark=",", scientific=FALSE))

    head(data[, c('Species', 'Sepal.Length')])
  Species Sepal.Length
1  setosa $510,000,000
2  setosa $490,000,000
3  setosa $470,000,000
4  setosa $460,000,000
5  setosa $500,000,000
6  setosa $540,000,000

You can use scales::dollar

data$Sepal.Length <- scales::dollar(data$Sepal.Length)
head(data[, c('Species', 'Sepal.Length')])

#  Species Sepal.Length
#1  setosa $510,000,000
#2  setosa $490,000,000
#3  setosa $470,000,000
#4  setosa $460,000,000
#5  setosa $500,000,000
#6  setosa $540,000,000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM