cconnell
cconnell

Reputation: 863

How to convert a column of formulas to include the data frame prefix in R

How would I convert a column of R formulas to include the data frame specification? For example I have a column of hundreds of formulas, but they don't contain any data frame spec, such as:

365/(x/y)
365/(x/(y + z))
365/(x/ (y - z))
c + d + e + f

and I would like to convert the whole column to look like:

365/(r$x/r$y)
365/(r$x/(r$y + r$z))
365/(r$x/ (r$y - r$z))
r$c + r$d + r$e + r$f

so I basically want to add a prefix(r$) to each text group separated by operators. is this possible to do in R?

Upvotes: 0

Views: 141

Answers (2)

IRTFM
IRTFM

Reputation: 263362

The usual way to do this is to wrap a formula (or more accurately an expression) in with(). You will need to eval()-uate each expression in the context of the environment created by the with "closure" if you want to produce a resultant vector.

expr <- expression(365/(x/y),
 365/(x/(y + z)),
 365/(x/ (y - z)),
 c + d + e + f)
dat <- data.frame(x=sample(1:100, 10),
  y=sample(1:100, 10),
  z=sample(1:100, 10),
  c=sample(1:100, 10),
  d=sample(1:100, 10),
  e=sample(1:100, 10),
  f=sample(1:100, 10))
 sapply(expr, function(ep) with(dat, eval(ep)))
            [,1]       [,2]         [,3] [,4]
 [1,]  121.66667  1155.8333   -912.50000  168
 [2,] 4197.50000  4471.2500   3923.75000  131
 [3,]  290.00000   620.0000    -40.00000  219
 [4,]   60.83333  3224.1667  -3102.50000  245
 [5,] 6752.50000 24637.5000 -11132.50000  229
 [6,] 4901.42857  7456.4286   2346.42857  239
 [7,]  127.75000   246.3750      9.12500  177
 [8,]  355.64103  1179.2308   -467.94872  142
 [9,]  500.18519   959.8148     40.55556  161
[10,]  299.48718   444.5513    154.42308  194

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368261

A much better approach is to supply the data frame directly as e.g.

lm(y ~ x, data=myframe)

as many modelling function support a data= argument.

Alternatively, you can use the with and within functions

with(myframe, summary( 365/(x/y) ) )

which provide access to the components of the data frame myframe without requiring the prefix.

Upvotes: 3

Related Questions