0

I have a data frame with several columns, I need to subtract the values of two columns from this data frame and add the resulted values as a new column in the same dataset.

Any idea on how to write function in R to do so?

Thanks in advance

Far

Tung
  • 26,371
  • 7
  • 91
  • 115
Fahimeh Falahi
  • 21
  • 1
  • 1
  • 1
  • 3
    Welcome to Stackoverflow. What did you try? Why did it fail? – lukeA Feb 03 '16 at 13:36
  • 4
    data$newvalue <- data$var1 - data$var2? If this is indeed the answer, you will very likely benefit from reading some introductory materials on R. – Heroka Feb 03 '16 at 13:47
  • Related https://stackoverflow.com/questions/28858393/subtract-a-column-in-a-dataframe-from-many-columns-in-r/ – Tung Nov 05 '19 at 14:27

2 Answers2

4

Okay, let's say we have a data frame with two numeric columns, num1 and num2 (possibly with other columns too), which might look something like this:

    num1 num2
1    3   12
2    6   13
3    9   14
4   12   15
5   15   16

If we select the two columns and subtract one from the other, R automatically just subtracts their components element-wise, so this makes sense to try. Also, by setting the value of a new column, R automatically creates this column for us and adds it to the data frame (thanks Vongo for pointing this out in a comment).

Therefore, if we want to subtract column 'num1' from column 'num2' and add it as another column 'num3' to our data frame called 'df', we could try:

df$num3 <- df$num2 - df$num1

This gives the following data frame:

    num1 num2 num3
1    3   12    9
2    6   13    7
3    9   14    5
4   12   15    3
5   15   16    1

I hope that helps!

Note: if you want to reproduce the data frame I made for this example, the following two lines of code should do the trick:

df <- data.frame(3*1:5, 12:16)
names(df) <- c('num1', 'num2')
hodgenovice
  • 624
  • 3
  • 14
0

One simple way is to add another column to your existing data frame and populate it with the result. See an example below

DF = data.frame(num1 = runif(10, min = 1, max = 5), num2 = runif(10, min = 10, max = 15))
DF$num3 = DF$num2 - DF$num1
CForClimate
  • 335
  • 5
  • 19