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
?
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
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