Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change all columns except the 1st to dollar format

Tags:

r

dplyr

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?

like image 885
nak5120 Avatar asked Feb 06 '17 17:02

nak5120


People also ask

How to change data type for one or more columns in pandas?

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.

How do I change the currency in Excel 2016?

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.

How do I change the currency symbol in accounting number format?

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.

How to change all columns of a Dataframe to a specific type?

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.


1 Answers

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)
like image 65
akrun Avatar answered Sep 28 '22 15:09

akrun