How to write an R function that evaluates an expression within a data-frame

前端 未结 4 1575
梦谈多话
梦谈多话 2020-12-05 16:09

Puzzle for the R cognoscenti: Say we have a data-frame:

df <- data.frame( a = 1:5, b = 1:5 )

I know we can do things like



        
4条回答
  •  伪装坚强ぢ
    2020-12-05 16:32

    The lattice package does this sort of thing in a different way. See, e.g., lattice:::xyplot.formula.

    fn <- function(dat, expr) {
      eval(substitute(expr), dat)
    }
    fn(df, a)             # 1 2 3 4 5
    fn(df, 2 * a + b)     # 3 6 9 12 15
    

提交回复
热议问题