I want to create a function that takes the arguments as column names in my dataset.
However when I pass this function with my desired column names as arguments the mutated columns use the literal argument name instead of the passed column names (parameter instead of "cpp").
vehicle <- c("airplane", "bus", "car")
people <- c(300, 40, 5)
cost <- c(50, 5, 2)
small_dataset <- data.frame(vehicle, people, cost)
func <- function(data, parameter) {
data <- data %>%
mutate(parameter = cost/people)
return(data)
}
func(small_dataset, "cpp")
WHAT I WANT:
## vehicle people cost cpp
## 1 airplane 300 50 0.1666667
## 2 bus 40 5 0.1250000
## 3 car 5 2 0.4000000
WHAT I GET:
## vehicle people cost parameter
## 1 airplane 300 50 0.1666667
## 2 bus 40 5 0.1250000
## 3 car 5 2 0.4000000
How do I get the function to use the arguments as column names?
Perhaps cleaner here to use base R (instead of dplyr):
func <- function(data, parameter) {
data[[parameter]] <- with(data, cost/people)
data
}
func(small_dataset, "cpp")
# vehicle people cost cpp
# 1 airplane 300 50 0.1666667
# 2 bus 40 5 0.1250000
# 3 car 5 2 0.4000000
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