R: Evaluate an expression in a data frame with arguments that are passed as an object

前端 未结 1 338
广开言路
广开言路 2021-01-12 19:35

I want to write a function that evaluates an expression in a data frame, but one that does so using expressions that may or may not contain user-defined objects. I think the

相关标签:
1条回答
  • 2021-01-12 19:55

    From ?lm, re data argument:

    If not found in data, the variables are taken from environment(formula)

    In your first case, the formula is created in your eval(expr, df, pf) call, so the environment of the formula is an environment based on df. In the second case, the formula is created in the global environment, which is why it doesn't work.

    Because formulas come with their own environment, they can be tricky to handle in NSE.

    You could try:

    with(mydf,
      {
        print(lm(y~x))
        fml <- y~x
        print(lm(fml))
      }
    )
    

    but that probably isn't ideal for you. Short of checking whether any names in the captured parameter resolve to formulas, and re-assigning their environments, you'll have some trouble. Worse, it isn't even necessarily obvious that re-assigning the environment is the right thing to do. In many cases, you do want to look in the formula environment.

    There was a loosely related discussion on this issue on R Chat:

    • Ben Bolker outlines an issue
    • Josh O'Brien points to some old references
    0 讨论(0)
提交回复
热议问题