1

I have a dataframe like this:

Element    Variable
      A       Power
      A     Current
      B       Power

I'd like to combine those rows that are equal in Element separating the conent of the rows by comas:

Element            Variable
      A      Power, Current
      B               Power
Maël
  • 45,206
  • 3
  • 29
  • 67
MustardRecord
  • 305
  • 4
  • 14

1 Answers1

3

base R

Use aggregate and toString:

aggregate(Variable ~ Element, df, toString) #toString can be replaced by paste here

  Element       Variable
1       A Power, Current
2       B          Power

dplyr

Use group_by and toString:

df %>%
  group_by(Element) %>%
  summarise(test = toString(Variable)) %>%
  ungroup()

Data

df <- data.frame(Element = c('A', 'A', 'B'), Variable = c('Power', 'Current', 'Power'))
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    Neat @Maël. Superfluously, for those not familiar with `aggregate()`, `Variable ~ .` is equivalent to `Variable ~ Element`. – Dion Groothof Jan 11 '22 at 15:32
  • 1
    Yes, and it actually make more sense here to do it with Element present. edited ;) – Maël Jan 11 '22 at 15:33