Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create new columns with mutate_all

Tags:

r

dplyr

I have some data that looks like this:

  Year Revenue Cost Rent
1 2016    3000    4  100
2 2017    4000    5  100
3 2018    5000    6  100

df <- data.frame(stringsAsFactors=FALSE,
        Year = c(2016L, 2017L, 2018L),
     Revenue = c(3000L, 4000L, 5000L),
        Cost = c(4L, 5L, 6L),
        Rent = c(100L, 100L, 100L)
)

I'd like to divide everything say as a percentage of Rent:

library(dplyr)
df <- df %>% mutate_at(vars(Revenue:Rent), funs(. /Rent))

which works perfectly.

  Year Revenue Cost Rent
1 2016      30 0.04    1
2 2017      40 0.05    1
3 2018      50 0.06    1

The only thing: I've lost my original columns.

How can I do the mutate_all, so that I have new columns, say called Revenue_percentage_of_rent, Cost_percentage_of_rent ?

like image 366
Jeremy K. Avatar asked Mar 14 '19 02:03

Jeremy K.


1 Answers

The usage of funs would be deprecated in favor of list from dplyr_0.8.0 So, the option would be

library(dplyr)
df %>%
    mutate_at(vars(Revenue:Rent), list(percentage_of_rent = ~  ./Rent))
#  Year Revenue Cost Rent Revenue_percentage_of_rent Cost_percentage_of_rent Rent_percentage_of_rent
#1 2016    3000    4  100                         30                    0.04                       1
#2 2017    4000    5  100                         40                    0.05                       1
#3 2018    5000    6  100                         50                    0.06                       1
like image 114
akrun Avatar answered Sep 29 '22 11:09

akrun