Faseeh Ahmed
Faseeh Ahmed

Reputation: 21

How to merge two rows in R?

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!

Upvotes: 2

Views: 1695

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

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 

Upvotes: 1

Related Questions