對編程有些陌生,我想嘗試使 R 中的自定義函式更易于使用,并且減少冗余。
在使用時如何從看起來像這樣的自定義函式中去:
Function(data=df, x=df$x, y=df$y)
進入:
Function(data=df, x=x, y=y)
因為我的函式定義現在看起來像這樣:
Function <- function(data, x, y){ does whatever… }
具體來說,我不想對每個變數輸入都使用 $ 運算子。我只想使用我擁有的 df 作為“資料”的引數。我將如何以不同的方式設定它?
謝謝!
uj5u.com熱心網友回復:
你可以去 enqouting 你的論點像這樣
sum2vars <- function(data, x, y) {
x <- rlang::ensym(x)
y <- rlang::ensym(y)
data[[x]] data[[y]]
}
sum2vars(mtcars, mpg, am)
#> [1] 22.0 22.0 23.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 33.4 31.4 34.9 21.5 15.5 15.2 13.3 19.2 28.3 27.0 31.4 16.8 20.7
#> [31] 16.0 22.4
在 tidyverse 中,您可以使用擁抱方法
plot2vars <- function(data, x, y) {
ggplot2::ggplot(data, ggplot2::aes(x = {{ x }}, y = {{ y }}))
ggplot2::geom_point()
}
plot2vars(mtcars, wt, mpg)

有關更多詳細資訊,請閱讀Advance R 一書的第 19章
還有這篇關于tidyverse 編程的帖子
使用reprex v2.0.2創建于 2022-10-10
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513413.html
標籤:r
