使用另一个变量的公式为数据框创建新列 [英] Creating a new column to a data frame using a formula from another variable

查看:77
本文介绍了使用另一个变量的公式为数据框创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用另一个变量的公式为数据框创建新列。

示例:

我有一个数据集 aa是;

I want to create a new column to a data frame using a formula from another variable.
Example:
I have a data set "aa" is;

x    y 
2    3 
4    5 
6    7 

我的R代码是;

>bb <- "x+y-2" 
>attach(aa) 
>aa$z<- bb 
>detach(aa) 

结果是;

x  y  z 
2  3  x+y-2 
4  5  x+y-2 
6  7  x+y-2 

但我想要这样;

x  y  z 
2  3  3 
4  5  7 
6  7  11 

能否请你帮帮我。.

推荐答案

如果要在数据帧的上下文中求值表达式,可以在 with within

If you want to evaluate an expression in the context, of a data frame, you can use with and within.

aa$z <- with(aa, x + y - 2)

aa <- within(aa, z <- x + y - 2)

或者您的表达式是以文本字符串的形式出现的(您应该查看是否还有其他方式编写代码;评估任意文本字符串会导致很多问题):

Or, if your expression is in the form of a text string (you should see if there are other ways to write your code; evaluating arbitrary text strings can lead to lots of problems):

aa$z <- eval(parse(text="x + y - 2"), aa)

这篇关于使用另一个变量的公式为数据框创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆