Updating a data.frame column with eval function

白昼怎懂夜的黑 提交于 2019-12-24 12:33:52

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/23508270/updating-a-data-frame-column-with-eval-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!