[英]How can I access a column name within a function in a mutate call?
我正在使用我寫的 function 改變一列以在 R 中創建一個新列。
在我的 function 中,我想發送一條消息,其中包含正在更改的列的名稱。
如何在 mutate 調用中從 function 內部訪問正在變異的列名?
可重現的例子:
data <- tribble(
~colB,
1,
2,
3
)
# Function that will be used in the mutate
add1 <- function(numeric_vector) {
return(1 +numeric_vector)
# I want to message the user the name of the column they are mutating
# This simply returns the entire vector
message("You mutated", numeric vector)
# This returns 'numeric_vector'
message("You mutated", quo_name(quo(numeric_vector)))
}
# Desired Output:
data %>%
mutate(colC = add1(colB))
You mutated colB
colB colC
<dbl> <dbl>
1 2
2 3
3 4
使用返回name
class object 的substitute
。 我們將message
調用包裝在on.exit
中,以確保它在計算之后運行,以便在計算失敗時不會運行。 如果這不重要,則將on.exit(message(...))
替換為message(...)
。 請注意, add1
本身不使用任何包。
library(dplyr)
add1 <- function(numeric_vector) {
on.exit(message("You mutated ", substitute(numeric_vector)))
1 + numeric_vector
}
BOD %>% mutate(Time = add1(Time))
給予:
You mutated Time
Time demand
1 2 8.3
2 3 10.3
3 4 19.0
4 5 16.0
5 6 15.6
6 8 19.8
要使用 rlang,請使用enexpr
中的 enexpr。 dplyr 將使其可用。 enexpr
返回name
class object。
enexpr
類似於substitute
,但會影響處理的一個區別是substitute
將提取 promise 的代碼部分,無論 promise 是否已被強制(即評估); 然而, enexpr
將提取非強制承諾的代碼,但會提取強制承諾的值。 由於我們需要代碼部分,我們必須確保在計算中使用numeric_vector
之前運行enexpr(numeric_vector)
。 為了確保我們引入了一個新變量arg_name
,它在開始時運行,確保enexpr
具有非強制參數。
library(dplyr)
add2 <- function(numeric_vector) {
arg_name <- enexpr(numeric_vector)
on.exit(message("You mutated ", arg_name))
1 + numeric_vector
}
BOD %>% mutate(Time = add2(Time))
我想你想要
add1 <- function(numeric_vector) {
message(paste("You mutated", quo_name(enquo(numeric_vector))))
return(1 + numeric_vector)
}
請注意,您必須在return()
之前打印您的消息。 return()
之后的任何內容都不會在 function 中運行,因為您在點擊該語句時退出。 此外,您可以使用enquo()
來獲取變量以獲取其名稱。 你需要在它還在 promise state 的時候得到它的名字,所以這意味着在你實際使用它的價值之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.