使用eval函数更新data.frame列 [英] Updating a data.frame column with eval function
问题描述
eval(或以任何其他方式)函数更新其中一列在另一列中的值。 Col1
是一个字符列,我需要评估表达式并更新 Col2
中的结果。
所以,对于第一行它将是-0.49,最后一个:-0.26。
我尝试了这种方法,但它更新了所有的值与上一行的评估结果: 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
我有这个意想不到的结果:
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
解决方案看来如果你通过 eval
一个表达式的向量,它只返回最后一个结果。我不知道为什么这是所期望的行为,但这是如何记录在?eval
帮助页面上:
(函数返回)评估对象的结果:对于表达式向量,这是评估最后一个元素的结果。
所以你可以用一个友好的 sapply
语句来解决这个问题。
sapply(df $ Col1,function(x)eval(parse(text = x)))
那应该给你你期望的结果的向量。
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
解决方案 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.
这篇关于使用eval函数更新data.frame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!