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?

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Thanks - I think I figured it out. For some reason the "Value" header wasn't being picked up appropriately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.