R: collapse dataframe with similar rows

Viewed 53

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
1 Answers

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'))
Related