Reputation: 1792
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
?
Upvotes: 6
Views: 801
Reputation: 887951
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
Upvotes: 5
Reputation: 389325
Name the column in the function in mutate_at
library(dplyr)
df %>% mutate_at(vars(Revenue:Rent), funs(percentage_of_rent = . /Rent))
You can do it with mutate_all
but then it will also divide the Year
column by Rent
which I suppose you don't need.
A workaround to use mutate_all
would be
df %>% select(-Year) %>% mutate_all(funs(percentage_of_rent = . /Rent))
but you loose Year
column here.
Upvotes: 2