簡體   English   中英

字符串作為函數參數r

[英]character string as function argument r

我正在使用dplyr並創建了代碼來計算用ggplot繪制的新數據。

我想用此代碼創建一個函數。 它應該使用由dplyr操作的數據框的列的名稱。 但是,嘗試使用列名不起作用。 請考慮以下最小示例:

df <- data.frame(A = seq(-5, 5, 1), B = seq(0,10,1))

library(dplyr)
foo <- function (x) {
         df %>%
            filter(x < 1)
}

foo(B)

Error in filter_impl(.data, dots(...), environment()) : 
  object 'B' not found 

有什么解決方案可以將列名用作函數參數?

如果要創建一個接受字符串“ B”作為參數的函數(如問題標題所示)

foo_string <- function (x) {
         eval(substitute(df %>% filter(xx < 1),list(xx=as.name(x))))
}
foo_string("B")

如果要創建一個將捕獲B作為參數的函數(如dplyr)

foo_nse <- function (x) {
         # capture the argument without evaluating it
         x <- substitute(x)
         eval(substitute(df %>% filter(xx < 1),list(xx=x)))
}
foo_nse(B)

您可以在Advanced R中找到更多信息。

編輯

dplyr在0.3版dplyr事情變得更容易。 帶后綴“ _”的函數接受字符串或表達式作為參數

 foo_string <- function (x) {
             # construct the string
             string <- paste(x,"< 1")
             # use filter_ instead of filter
             df %>% filter_(string)
    }
foo_string("B")
 foo_nse <- function (x) {
             # capture the argument without evaluating it
             x <- substitute(x)
             # construct the expression
             expression <- lazyeval::interp(quote(xx < 1), xx = x)
             # use filter_ instead of filter
             df %>% filter_(expression)
    }
foo_nse(B)

您可以在此小插圖中找到更多信息

我記得@Richard Scriven回答了類似的問題。 我認為您需要編寫這樣的內容。

foo <- function(x,...)filter(x,...) 

@Richard Scriven提到的是,您需要在這里使用... 如果鍵入?dplyr,將可以找到以下內容: filter(.data, ...)我認為您可以用x或其他替換.data。 如果要在df中拾取值小於B中1的行,則將像這樣。

foo <- function (x,...) filter(x,...)
foo(df, B < 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM