I am trying to apply functions across several variables in a data frame. Below is an example of what I'm trying to do.
#Creating data frame
df <- data.frame (Year = c(1,2,3),
"Revenue_change" = c(0.43, 0.56, 0.48),
"Costs_change" = c(0.31, 0.41, 0.39))
#Create vector to use for loop
var <- c("Revenue_change", "Costs_change")
#Using loop to put revenue and cost in percentage terms (multiplying by a 100)
for (v in var) {
df <- df %>%
mutate(v = v * 100)
}
I will be applying this across several variables in a much bigger data frame and because I can't get this loop to work in my main dataset, I currently have very repetitive code as shown below:
KPI <- KPI %>%
#Total sales
mutate(Rank_sales = rank(desc(`Total Sales_% Var`))) %>%
mutate(Points_sales = (n() - (Rank_sales - 1)) * 10) %>%
#Donated sales
mutate(Rank_donated = rank(desc(`Donated Sales_% Var`))) %>%
mutate(Points_donated = (n() - (Rank_donated - 1)) * 10) %>%
#New good sales
mutate(Rank_new = rank(desc(`New Goods Sales_% Var`))) %>%
mutate(Points_new = (n() - (Rank_new - 1)) * 10) %>%
#Gift aid
mutate(Rank_gift = rank(desc(`Gift Aid_%`))) %>%
mutate(Points_gift = (n() - (Rank_gift - 1)) * 10) %>%
#Net profit
mutate(Rank_net = rank(desc(`Net Profit_£ Var`))) %>%
mutate(Points_net = (n() - (Rank_net - 1)) * 10) %>%
#Volunteer
mutate(Rank_volunteer = rank(desc(`Volunteer Hrs_for every £1k Sales`))) %>%
mutate(Points_volunteer = (n() - (Rank_volunteer - 1)) * 10)
Hopefully a loop or apply function will help reduce the repetitiveness of the current code.
Hard to test if it actually works without a sample of your actual data, but something like this should work:
myvars <- c("Total Sales_% Var", "Donated Sales_% Var", "New Goods Sales_% Var", "Gift Aid_%", "Net Profit_£ Var", "Volunteer Hrs_for every £1k Sales")
Points_fun <- function(x) {
rank_var <- rank(desc(x))
(n() - (rank_var - 1)) * 10)
}
mutate(KPI, across(all_of(myvars), ~ rank(desc(.x)), .names = "Rank_{.col}"),
across(all_of(myvars), Points_fun, .names = "Points_{.col}"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.