Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new rows to a data frame with values computed from existing rows

Tags:

r

dplyr

With a dataframe df like below

text <- "
Parameter,Dec-17,Sep-17,Jun-17,Mar-17,Dec-16
Income,12112,13323.2,14655.52,16121.072,17733.1792
Cost,10900.8,11990.88,13189.968,14508.9648,15959.86128
"
df <- read.table(textConnection(text), sep=",", header = T, stringsAsFactors = F)
df

  Parameter  Dec.17   Sep.17   Jun.17   Mar.17   Dec.16
1    Income 12112.0 13323.20 14655.52 16121.07 17733.18
2      Cost 10900.8 11990.88 13189.97 14508.96 15959.86

I want to add two more rows, 1- Profit (Income - Cost) and 2 - Tax ( 0.2* Profit) for each of the quarters - Dec.17, Sep.17, Jun.17, Mar.17, Dec.16

How do I got about this - dplyr is preferred. Base R solution would be also helpful.

Expected output

  Parameter   Dec.17    Sep.17     Jun.17     Mar.17     Dec.16
1    Income 12112.00 13323.200 14655.5200 16121.0720 17733.1792
2      Cost 10900.80 11990.880 13189.9680 14508.9648 15959.8613
3    Profit  1211.20  1332.320  1465.5520  1612.1072  1773.3179
4       Tax   242.24   266.464   293.1104   322.4214   354.6636
like image 345
user3206440 Avatar asked Dec 31 '25 09:12

user3206440


1 Answers

Maybe not the most elegant, but this is a dplyr solution. The last select is to get the same column order as the original table.

df %>%
  gather(key = month, value = amount, -Parameter) %>%
  spread(Parameter, amount) %>%
  mutate(Profit = Income - Cost) %>%
  mutate(Tax = 0.2 * Profit) %>%
  gather(key = Parameter, value = amount, -month) %>%
  spread(month, value = amount) %>%
  select(names(df))

Parameter   Dec.17    Sep.17     Jun.17     Mar.17     Dec.16
1      Cost 10900.80 11990.880 13189.9680 14508.9648 15959.8613
2    Income 12112.00 13323.200 14655.5200 16121.0720 17733.1792
3    Profit  1211.20  1332.320  1465.5520  1612.1072  1773.3179
4       Tax   242.24   266.464   293.1104   322.4214   354.6636
like image 157
gatsky Avatar answered Jan 03 '26 03:01

gatsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!