1

For the below dataframe AB, the formula values i.e. b,c,d,e,f,z,x,y etc. are in a different dataframe lets say DF.

I wish to fill the values for each item based on corresponding formula. Using eval(parse) didn't work

Here is what I had

AB$Value<-eval(parse(text="c+d-2"),DF)

   Item  Value  Formula 
    A      -      c+d-2 
    B      -      x+b-2 
    C      -      z+y-2 
    D      -      e+f

DF

Code     Value 
b       1
c       5
d       6
e       9
f       13
x       15
y       20
z        2

How do I iterate so that all values get filled based on corresponding formula?

oivemaria
  • 453
  • 4
  • 20

1 Answers1

3

parse the column, coerce it to a list and sapply the eval across it (as in the second solution of this SO post) :

L <- with(DF, as.list(setNames(Value, Code)))
transform(AB, Value = sapply(as.list(parse(text = Formula)), eval, L))

giving:

  Item Value Formula
1    A     9   c+d-2
2    B    14   x+b-2
3    C    20   z+y-2
4    D    22     e+f

Note: We used these inputs:

Lines <- "Item  Value  Formula 
A      -      c+d-2 
B      -      x+b-2 
C      -      z+y-2 
D      -      e+f"
AB <- read.table(text = Lines, header = TRUE, as.is = TRUE)

Lines2 <- "Code     Value 
b       1
c       5
d       6
e       9
f       13
x       15
y       20
z        2"
DF <- read.table(text = Lines2, header = TRUE, as.is = TRUE)
Community
  • 1
  • 1
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks this seems to have worked except that the empty column "Value" that I already have in my dataframe doesn't get populated and a fresh "Value" column gets created. – oivemaria Mar 18 '16 at 04:50
  • Presumably your setup differs in some way you haven't explained. The code and inputs above are all reproducible and do not result in a new additional `Value` column on my machine as can be seen by the output which is shown. – G. Grothendieck Mar 18 '16 at 12:57
  • Thanks - I think I figured it out. For some reason the "Value" header wasn't being picked up appropriately – oivemaria Mar 18 '16 at 14:22