0

I have one question. I have one date base with two variables in two columns, the brand and the price. For example: 2 brands and their prices

BRAND PRICE

A 10.5

A 11.5

A 12.5

B 9.8

B 9.5

And there are more brands and prices.

I'd like to transform the data and put in each row the brand without duplicates and the prices in one column but all together as factor and separated by commas

It was this way:

BRAND PRICE

A {10.5,11.5,12.5}

B {9.8,9.5}

Could someone help me with this?

Thank you

Below one example the data original

enter image description here

Mérek
  • 1
  • 1

1 Answers1

0

Welcome to stackoverflow. In the future, see the how to make a great reproducible example post for asking questions.

What I think you want to do is just group and concatenate. Concatenate strings by group with dplyr

Since you only want unique brands, you'll just slice it.

library(dplyr)

df <- data.frame(brand = c("A", "A", "A", "B", "B"), price = c(10.5,11.5,12.5,9.8,9.5))

df %>% 
  group_by(brand) %>% 
  mutate(brand_price = paste0(price, collapse = ",")) %>% 
  select(brand, brand_price) %>% 
  slice(1)

> tdf
# A tibble: 2 x 2
# Groups:   brand [2]
  brand brand_price   
  <fct> <chr>         
1 A     10.5,11.5,12.5
2 B     9.8,9.5  
Anonymous coward
  • 2,061
  • 1
  • 16
  • 29
  • Thank you so much indeed for your quick answer!! It works. Next times i'll write the questions with your recomendation. – Mérek Apr 01 '20 at 20:29