2016-07-31 7 views
1

추가 계산을 수행하기 위해 lm 주위에 래퍼를 작성 중입니다. 래퍼가 ...lm에 전달하고 싶지만, lmweights 인수에 문제가 있습니다.줄임표 문제 : 전달 중 ... lm

LmWrapper <- function(df, fmla, ...) { 
    est <- lm(fmla, df, ...) 
    list(model = est) 
} 

나는 무게 인수와 함께 래퍼를 호출 할 경우,

data(airquality) 
LmWrapper(airquality, Ozone ~ Wind, weights = Temp) 

R은 무게를 찾을 방법을 알고하지 않습니다

Error in eval(expr, envir, enclos) : 
    ..1 used in an incorrect context, no ... to look in 

lm 도움말 페이지가

을 말한다

모두 weights, subsetoffsetformula의 변수와 동일한 방식으로 계산됩니다. 즉, 처음에는 data, 그 다음은 formula입니다.

하지만 래퍼가 변경되는 것처럼 보입니다.

어떻게 수정합니까? ,

8: eval(expr, envir, enclos) 
7: eval(extras, data, env) 
6: model.frame.default(formula = fmla, data = df, weights = ..1, 
     drop.unused.levels = TRUE) 
5: stats::model.frame(formula = fmla, data = df, weights = ..1, 
     drop.unused.levels = TRUE) 
4: eval(expr, envir, enclos) 
3: eval(mf, parent.frame()) 
2: lm(fmla, df, ...) at #2 
1: LmWrapper(diamonds, price ~ carat, weights = depth) 

직접 lm를 호출 잘 작동 : 위의 오류에 대한

traceback()


은 다음과 같습니다

lm(Ozone ~ Wind, airquality, weights = Temp) 

답변

2

그래서 문제가 lm 일반적으로 그 이름을 보이는 것입니다 인수 데이터에 있지만 어떤 식 으로든 범위 지정이 잘못되었습니다. 열 참조를 찾아 수동으로 전달하여이를 수정할 수 있습니다.

LmWrapper <- function(df, fmla, ...) { 
    # get names of stuff in ... 
    argNames = sapply(substitute(list(...))[-1L], deparse) 
    # look for identical names in df 
    m = match(names(df), argNames, 0L) 
    # store other arguments from ... in a list 
    args = list(eval(parse(text = argNames[-m]))) 
    # name the list 
    names(args) = names(argNames[-m]) 
    # store complete values in args, instead of just references to columns 
    # the unlist code is rather ugly, the goal is to create a list where every 
    # element is a column of interest 
    args[names(argNames)[m]] = unlist(apply(df[, as.logical(m), drop = FALSE], 
             2, list), recursive = FALSE) 
    # also put other stuff in there 
    args$formula = fmla 
    args$data = df 
    # do lm 
    est = do.call(lm, args) 
    list(model = est) 
} 

data(airquality) 

airquality$subset = airquality$Solar.R > 200 
LmWrapper(airquality, Ozone ~ Wind, weights = Temp, subset = subset, 
      method = 'qr') 

위의 코드는 가장 아름다운 아니지만, subsetweights 모두 작동합니다. 또는 weightssubset을 예외로 처리 할 수도 있습니다.