Ant
Ant

Reputation: 343

Add extra row to dataframe based on values of other rows

I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0

I would like to add an extra row with a calculation to give the change across the two months:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.

Upvotes: 0

Views: 1360

Answers (3)

akrun
akrun

Reputation: 887108

An option with tidyverse

library(tidyverse)
df1 %>% 
    summarise_if(is.numeric, diff) %>%
    abs %>%
    bind_rows(df1, .) %>%
    mutate(Month = replace_na(Month, "Change"))
#   Month A B C D E F
#1    Jan 1 2 4 8 4 1
#2    Feb 1 1 4 5 2 0
#3 Change 0 1 0 3 2 1

data

df1 <- structure(list(Month = c("Jan", "Feb"), A = c(1L, 1L), B = 2:1, 
    C = c(4L, 4L), D = c(8L, 5L), E = c(4L, 2L), F = 1:0),
    class = "data.frame", row.names = c(NA, 
-2L))

Upvotes: 1

DHRUV BATTA
DHRUV BATTA

Reputation: 1

d1<-data.frame(Month = "Change" , df[1,-1] , df[2,-1])
newdf <- rbind(df,d1)

This will create a new data-frame with what you require

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

As it's just two rows you can subtract the individual rows and rbind the difference

rbind(df, data.frame(Month = "Change", df[1, -1] - df[2, -1]))

#   Month A B C D E F
#1    Jan 1 2 4 8 4 1
#2    Feb 1 1 4 5 2 0
#3 Change 0 1 0 3 2 1

Upvotes: 2

Related Questions