2

I wanted to know if there is a function in R that will help me merge two rows. Right now my data is in the following shape

Car_Type Prod Sale Month
Civic 120 67 June
City 192 112 June

If possible, I would like the data to take this shape:

Car_Type Prod Sale Month
Civic + City 312 179 June

I have tried the aggregate function, which works, but it does not manipulate the entire data frame.

Any leads would be appreciated. Thanks!

  • 1
    ``df %>% group_by(Month) %>% summarise(Prod = sum(Prod), Sale = sum(Sale), Car_Type = paste0(Car_Type, collapse=" + "))`` – user438383 Dec 11 '21 at 09:32

1 Answers1

1

Here is a dplyr solution. It uses an auxiliary function f to separate the cases of numeric and character vectors and applies the necessary transformation.

library(dplyr)

f <- function(x){
  if(is.numeric(x))
    sum(x)
  else if(any(x[-1] != x[1]))
    paste(x, collapse = "+")
  else x[1]
}

df1 %>%
  group_by(Month) %>%
  summarise(across(everything(), f)) %>%
  relocate(Month, .after = last_col())
## A tibble: 1 x 4
#  Car_Type    Prod  Sale Month
#  <chr>      <int> <int> <chr>
#1 Civic+City   312   179 June 
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66