Nick Knauer Nick Knauer - 6 days ago 5
R Question

Rbind Difference of rows

I want to determine the difference of each row and have that total difference rbinded at the end. Below is a sample dataset:

DATE <- as.Date(c('2016-11-28','2016-11-29'))
TYPE <- c('A', 'B')
Revenue <- c(2000, 1000)
Sales <- c(1000, 4000)
Price <- c(5.123, 10.234)
Material <- c(10000, 7342)
df<-data.frame(DATE, TYPE, Revenue, Sales, Price, Material)

df

DATE TYPE Revenue Sales Price Material
1 2016-11-28 A 2000 1000 5.123 10000
2 2016-11-29 B 1000 4000 10.234 7342


How Do I calculate the Difference of Each of the Columns to produce this total:

DATE TYPE Revenue Sales Price Material
1 2016-11-28 A 2000 1000 5.123 10000
2 2016-11-29 B 1000 4000 10.234 7342
3 DIFFERENCE -1000 3000 5.111 -2658


I can easily do it by columns but having trouble doing it by row.

Any help would be great thanks!

Answer

As 'DATE' is Date class, we may need to change it to character before proceeding with rbinding with string "DIFFERENCE". Other than that, subset the numeric columns of 'df', loop it with lapply, get the difference, concatenate with the 'DATE' and 'TYPE', and rbind with original dataset.

df$DATE <- as.character(df$DATE)
rbind(df, c(DATE = "DIFFERENCE", TYPE= NA, lapply(df[-(1:2)], diff)))
#        DATE TYPE Revenue Sales  Price Material
#1 2016-11-28    A    2000  1000  5.123    10000
#2 2016-11-29    B    1000  4000 10.234     7342
#3 DIFFERENCE <NA>   -1000  3000  5.111    -2658