Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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  

My R code is;

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

the result is;

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

but I want like this;

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

Could you please help me..

like image 783
Punith Avatar asked Sep 25 '13 08:09

Punith


People also ask

How do you create a new column in DataFrame based on another column?

Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.

How do I add a column to a DataFrame from another DataFrame in R?

To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.


2 Answers

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) 
like image 163
Hong Ooi Avatar answered Oct 18 '22 14:10

Hong Ooi


You should probably read some basic tutorials on R other than An Introduction to R as despite what is written there the $ notation is more sensible and easier to understand than attach/detach. Try this in the meantime.

aa <- data.frame(x = c(2, 4, 6), y = c(3, 5, 7)) 

Which gives:

> aa   x y 1 2 3 2 4 5 3 6 7 

Then enter:

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

Which gives:

> aa   x y  z 1 2 3  3 2 4 5  7 3 6 7 11 
like image 23
SlowLearner Avatar answered Oct 18 '22 14:10

SlowLearner