2

この機能を考慮してください:

tf <- function(formula = NULL, data = NULL, groups = NULL) {

    grv <- eval(substitute(groups), data, environment(formula)) # the values
    grn <- as.character(match.call()$groups) # the name
    gr <- match.call()$groups # unquoted name

    p <- xyplot(formula, data, # draws the data but not in groups
# Try these options:
#   p <- xyplot(formula, data, groups, # can't find 'cat2' 
#   p <- xyplot(formula, data, groups = data[,grn], # can't fine grn
#   p <- xyplot(formula, data, groups = grv, # can't find grv
        panel = function(x, y) {
            panel.stripplot(x, y, jitter.data = TRUE, pch = 20)
            }
            )
    p
    }

どちらで実行できますか:

tf(formula = mpg~vs, groups = am, data = mtcars)

groups引数をに渡す際に私が間違っているのは何xyplotですか?なぜそれが見つからないのですか?どうやってgroup情報が欲しいのかわからない。ありがとう。

アップデート:

@agstudyの回答は非常に役立ちますが、元の例のようにパネル関数を追加しても、グループはまだ認識されません(グループ化は行われませんが、エラーも発生しません)。

tf <- function(formula = NULL, data = NULL, groups = NULL) {
    ll <- as.list(match.call(expand.dots = FALSE)[-1])
    p <- xyplot(as.formula(ll$formula), 
              data = eval(ll$data), 
              groups = eval(ll$groups),
                panel = function(x, y) {
                panel.stripplot(x, y, jitter.data = TRUE, pch = 20)
                }
                )
    p
    }

まだ何かが足りない...ありがとう。

4

2 に答える 2

4

シンボルを返すevalので、ここで使用できます。match.call

tf <- function(formula = NULL, data = NULL, groups = NULL) {
  ll <- as.list(match.call(expand.dots = FALSE)[-1])
  p <- xyplot(as.formula(ll$formula), 
              data = eval(ll$data), 
              groups = eval(ll$groups),
              panel = function(x, y,...) { ## here ... contains groups and subscripts
                ## here you can transform x or y before giving them to the jitter
                panel.stripplot(x, y, jitter.data = TRUE, pch = 20,...)
              }
  )
  p
}
于 2013-02-09T07:01:23.100 に答える
2

関数内の関数のスコープと呼び出しに問題がある場合に使用する 1 つの手法は、パラメーターを文字列として渡し、それらの文字列から関数内の呼び出しを構築することです。これは、ここでどのように見えるかです。

panel2 <- function(x, y, ...) {panel.stripplot(x, y, jitter.data = TRUE, pch = 20, ...)}
tf <- function(formula, data, groups) {
  eval(call("xyplot", as.formula(formula), 
                      groups=as.name(groups), 
                      data=as.name(data),
                      panel=as.name("panel2")))
}

tf("mpg~vs", "mtcars", "am") 

この別の例については、以前の質問の 1 つに対するこの回答を参照してください: https://stackoverflow.com/a/7668846/210673

この質問の姉妹の質問に対するこの回答も参照してください。ここでは、 https aov: //stackoverflow.com/a/14858614/210673

于 2013-02-13T16:50:18.460 に答える