R: collapse dataframe with similar rows [duplicate]

Solution 1:

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