0

I'm new to this site (and new to R) so I hope this is the right way to approach my problem. I searched at this site but couldn't find the answer I'm looking for.

My problem is the following: I have imported a table from a database into R (it says it's a data frame) and I want to substract the values from a particular columnn (row by row). Thereafter, I'd like to assign these differences to a new column called 'Difference' in the same data frame.

Could anyone please tell me how to do this?

Many thanks, Arjan

Arjan
  • 137
  • 1
  • 7
  • Typically `DF$new_col <- DF$colA - DF$colB`. If that doesn't work, consider building an example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Mar 15 '18 at 16:06
  • Could you please add more information? – ecp Mar 15 '18 at 16:06

2 Answers2

0

To add a new column, just do df <- df$newcol, where df is the name of your data frame, and newcol is the name you want, in this case it would be "Difference". If you want to subtract an existing column using an existing column just use arithmetic operations.

df$Difference <- (df$col1 - df$col2)

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29
0

I'm going to assume you want to subtract the values in one column from another is this correct? This can be done pretty easily see code below.

first I'm just going to make up some data.

df <- data.frame(v1 = rnorm(10,100,4), v2 = rnorm(10,25,4))

You can subtract values in one column from another by doing just that (see below). Use $ to specify columns. Adding a new name after the $ will create a new column. (see code below)

df$Differences <- df$v1 - df$v2
df

          v1       v2 Differences
1   98.63754 29.54652    69.09102
2   99.49724 24.27766    75.21958
3  102.73056 25.01621    77.71435
4  100.87495 26.92563    73.94933
5  103.01357 17.46149    85.55208
6   97.24901 20.82983    76.41917
7  100.73915 27.95460    72.78454
8   98.14175 24.19351    73.94824
9  102.63738 21.74604    80.89133
10 105.78443 16.79960    88.98483

Hope this helps

THATguy
  • 292
  • 2
  • 11
  • Thank you all for your answers. However, I think I asked my question the wrong way. Assume I have the dataframe you made above with the columns v1 and v2. I'd like to subtract the values from column v1. So 99.49724- 98.63754 = 0.8597 and assign this outcome to the new column 'difference' – Arjan Mar 16 '18 at 07:57
  • I tried something with the ave function after I found out to change the values from the colum to numeric. And suddenly I got the correct difference column. – Arjan Mar 16 '18 at 08:51