How to add comma and percentage sign to particular column in R

Viewed 511

I have a dataframe in R which looks like.

Date         Art        Bst     Cde       Fet       Drt
2020-04-02   100000     14.34   1223400   15.23     12.22
2020-04-04   150000     12.33   103400    11.14     01.22
2020-04-05   1700000    11.45   1000000   17.41     10.22

The class of data frame is [1] "data.table" "data.frame". I want to add the comma after three-digit in columns 2,4 and the % sign in columns 3,5 and 6.

Required output:

Date         Art          Bst      Cde         Fet         Drt
2020-04-02   100,000      14.34 %  122,340,0   15.23 %     12.22 %
2020-04-04   150,000      12.33 %  103,400     11.14 %     01.22 %
2020-04-05   170,000,0    11.45 %  100,000,0   17.41 %     10.22 %
2 Answers

You can use base R in this way:

#Code
df$Art <- prettyNum(df$Art,big.mark = ',')
df$Cde <- prettyNum(df$Cde,big.mark = ',')
df$Bst <- paste0(df$Bst,' %')
df$Fet <- paste0(df$Fet,' %')
df$Drt <- paste0(df$Drt,' %')                            

Output:

df
        Date       Art     Bst       Cde     Fet     Drt
1 2020-04-02   100,000 14.34 % 1,223,400 15.23 % 12.22 %
2 2020-04-04   150,000 12.33 %   103,400 11.14 %  1.22 %
3 2020-04-05 1,700,000 11.45 % 1,000,000 17.41 % 10.22 %

Some data used:

#Data
df <- structure(list(Date = c("2020-04-02", "2020-04-04", "2020-04-05"
), Art = c(100000L, 150000L, 1700000L), Bst = c(14.34, 12.33, 
11.45), Cde = c(1223400L, 103400L, 1000000L), Fet = c(15.23, 
11.14, 17.41), Drt = c(12.22, 1.22, 10.22)), class = "data.frame", row.names = c(NA, 
-3L))

We can use comma and percent from formattable

library(dplyr)
library(formattable)
df2 <- df1 %>%
     mutate(across(c(Art, Cde), comma),
             across(c(Bst, Fet, Drt), ~ percent(.)/100))

-output

df2
#  Date          Art    Bst          Cde    Fet    Drt
#1 2020-04-02   100,000.00 14.34% 1,223,400.00 15.23% 12.22%
#2 2020-04-04   150,000.00 12.33%   103,400.00 11.14%  1.22%
#3 2020-04-05 1,700,000.00 11.45% 1,000,000.00 17.41% 10.22%

data

df1 <- structure(list(Date = c("2020-04-02", "2020-04-04", "2020-04-05"
), Art = c(100000L, 150000L, 1700000L), Bst = c(14.34, 12.33, 
11.45), Cde = c(1223400L, 103400L, 1000000L), Fet = c(15.23, 
11.14, 17.41), Drt = c(12.22, 1.22, 10.22)), class = "data.frame", 
row.names = c(NA, 
-3L))
Related