Creating a new column to a data frame using a formula from another variable

后端 未结 3 1768
醉梦人生
醉梦人生 2020-12-29 03:27

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             


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 04:17

    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)
    

    or

    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)
    

提交回复
热议问题