Fahimeh Falahi
Fahimeh Falahi

Reputation: 21

Subtract two columns in a data frame

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

Upvotes: 0

Views: 26882

Answers (2)

CForClimate
CForClimate

Reputation: 345

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

Upvotes: 0

hodgenovice
hodgenovice

Reputation: 624

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')

Upvotes: 4

Related Questions