Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
981 views
in Technique[技术] by (71.8m points)

r - Updating a data.frame column with eval function

I have a data.frame df with 2 columns in R and I need to update one of the columns by using a eval function (or by any other way) based on the values in the other column. Col1 is a character column and I need to evaluate the expression and update the result in Col2. So, for the first row it would be -0.49, for the last one: -0.26. I tried this approach but it updates all the values with the result from last row's evaluation:

df["Col2"] <- eval(parse(text=df$Col1))


Col1                     Col2
------------------------------
20.31 - 20.80            0
51.81 - 52.22            0
44.07 - 44.88            0
42.94 - 43.47            0
18.93 - 19.15            0
27.42 - 27.68            0

I got this unexpected result:

Col1                     Col2
------------------------------
20.31 - 20.80            -0.26
51.81 - 52.22            -0.26
44.07 - 44.88            -0.26
42.94 - 43.47            -0.26
18.93 - 19.15            -0.26
27.42 - 27.68            -0.26
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It appears that if you pass eval a vector of expressions, it only returns the last result. I'm not sure why that is the desired behavior, but that is how it is documented on the ?eval help page:

(The function returns) The result of evaluating the object: for an expression vector this is the result of evaluating the last element.

So you can get around this with a friendly sapply statement.

sapply(df$Col1, function(x) eval(parse(text=x)))

And that should give you the vector of results you were expecting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...