SNT
SNT

Reputation: 1433

Add specific rows to create new row using R dplyr

I am trying to add a new row Total which would be a sum of apples+bananas+oranges

      Metric_name         May      Jun 
1       apples             11       34       
2       bananas            632      640      
3       onions             479      503      
4       oranges            910      939    

How can I do it using dplyr

Upvotes: 0

Views: 5477

Answers (2)

pietrodito
pietrodito

Reputation: 2100

This is not absolute dplyr sytle because of the rbinds and I think there are better ways but this is a solution

df %>% 
  filter(Metric_name %in% c("apples", "bananas", "oranges")) %>% 
  rbind( c("Total", sum(.$May), sum(.$Jun)) ) %>% 
  filter(Metric_name == "Total") %>% 
  rbind(df, .)

# A tibble: 5 x 3
  Metric_name May   Jun  
  <chr>       <chr> <chr>   
1 apples      11    34   
2 bananas     632   640  
3 onions      479   503  
4 oranges     910   939  
5 Total       1553  1613 

PS: I have used that answer but I cannot do the same thing i.e. remove .$ before May and Jun when I make the sums

Upvotes: 1

phiver
phiver

Reputation: 23608

Just using dplyr, you can use bind_rows to add a row to the data.frame. In this case the outcome of a summarise statement. Because the outcome of the summarise is a data.frame with column names the columns will be added at the correct place and an empty value for the Metric_name. This we fill with the value Total if it has a NA value.

df1 %>% 
  bind_rows(df1 %>% 
            filter(Metric_name %in% c("apples","bananas","oranges")) %>% 
            summarise_if(is.numeric, funs(sum))) %>% 
  mutate(Metric_name = ifelse(is.na(Metric_name), "Total", Metric_name))

  Metric_name  May  Jun
1      apples   11   34
2     bananas  632  640
3      onions  479  503
4     oranges  910  939
5       Total 1553 1613

data:

df1 <- structure(list(Metric_name = c("apples", "bananas", "onions", 
"oranges"), May = c(11L, 632L, 479L, 910L), Jun = c(34L, 640L, 
503L, 939L)), class = "data.frame", row.names = c("1", "2", "3", 
"4"))

Upvotes: 1

Related Questions