[英]Using function arguments as column names
我想創建一個 function ,它將 arguments 作為我的數據集中的列名。
但是,當我將這個 function 與我想要的列名稱作為 arguments 一起傳遞時,變異的列使用文字參數名稱而不是傳遞的列名稱(參數而不是“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
如何讓 function 使用 arguments 作為列名?
有兩種選擇。 要么使用glue
語法:
library(glue)
func <- function(data, parameter) {
data %>%
mutate({{parameter}} := cost/people)
}
> 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
或 bang-bang 運算符!!
func <- function(data, parameter) {
data %>%
mutate(!!parameter := cost/people)
}
> 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
也許更清潔這里使用基礎 R (而不是 dplyr):
func <- function(data, parameter) {
data[[parameter]] <- with(small_dataset, 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
因為 data.frame 是一種特殊的列表,我們可以像這樣使用purrr::set_names
函數。 雖然不是很干凈。
library(purrr)
library(dplyr)
func <- function(data, parameter) {
data <- data %>%
mutate(parameter = cost / people) %>%
{
set_names(., c(names(.[-ncol(.)]), parameter))
}
return(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
由代表 package (v2.0.1) 於 2022 年 1 月 4 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.