I have a dataframe as follows:
A B C D E F G
AA 1 2 3 4 5 6
BB 3 2 1 9 23 2.6
CC 2 5 1 1.9 2.5 2.99
How do I change this dataframe to have all the columns converted to a dollar format using the scales package? For a single column I can just do this:
library(scales)
df$B<-dollar(df$B)
How do I do this for all the columns except the first one without writing this over and over again for each column?
Let’s see the different ways of changing Data Type for one or more columns in Pandas Dataframe. Method #1: Using DataFrame.astype () We can pass any Python, Numpy or Pandas datatype to change all columns of a dataframe to that type, or we can pass a dictionary having column names as keys and datatype as values to change type of selected columns.
On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting.
On the Home tab, in the Number group, click Accounting Number Format . If you want to show a currency symbol other than the default, click the arrow next to the Accounting Number Format button and then select another currency symbol.
We can pass any Python, Numpy or Pandas datatype to change all columns of a dataframe to that type, or we can pass a dictionary having column names as keys and datatype as values to change type of selected columns.
We can do this with lapply
df[-1] <- lapply(df[-1], dollar)
df
# A B C D E F G
#1 AA $1 $2 $3 $4.00 $5.00 $6.00
#2 BB $3 $2 $1 $9.00 $23.00 $2.60
#3 CC $2 $5 $1 $1.90 $2.50 $2.99
Or using tidyverse
library(tidyverse)
df %>%
mutate_at(vars(B:G), dollar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With