2

I have the following example data frame:

model <- c(1,1,1,1,2,2,3,3,3)

variable <- letters[seq(1:9)]

df <- data.frame(model , variable)

  model variable
1     1        a
2     1        b
3     1        c
4     1        d
5     2        e
6     2        f
7     3        g
8     3        h
9     3        i

and I would like to "collapse" the field variable grouped by model. If variable were numeric it would be a sum, or some other operator. However, this being character, I would like to paste the values.

  model variable
1     1  a b c d
2     2      e f
3     3    g h i
Illya-Big
  • 31
  • 4
  • 1
    If you wish to collapse several different columns, see [**here**](http://stackoverflow.com/questions/26981385/r-collapse-all-columns-by-an-id-column/26981611#26981611) – Henrik Dec 03 '14 at 13:53

3 Answers3

2

You can use aggregate:

aggregate(variable ~ model, df, paste, collapse = " ")
#   model variable
# 1     1  a b c d
# 2     2      e f
# 3     3    g h i
Sven Hohenstein
  • 78,180
  • 16
  • 134
  • 160
2

...or dcast from the reshape2 package:

> reshape2::dcast(df, model~., value.var = "variable", fun.aggregate = paste,
                  collapse = " ")
  model       .
1     1 a b c d
2     2     e f
3     3   g h i
krlmlr
  • 23,618
  • 14
  • 112
  • 204
1

Or using data.table

 library(data.table)
 setDT(df)[,  list(variable=paste(variable, collapse=' ')), by=model]
 #   model variable
 #1:     1  a b c d
 #2:     2      e f
 #3:     3    g h i
akrun
  • 789,025
  • 32
  • 460
  • 575