0

I have a dataset with columns ID, Score and Average age, using ddply(), I get the following table

ddply(data, .(id, score), summarize, group_mean = round(mean(avg_age), 1))

       id    score group_mean
1     101        0       61.8
2     101        5       70.3
3     101       10       62.2
4       2        0       41.0
5       2        5       40.4
6       2       10       44.5
7      23        0       52.0
8      23        5       52.6
9      25        0       74.5
10     25        5       55.2
11     25       10       48.0
12     28        0       53.4
13     28        5       49.5
14      3        0       41.3
15      3        5       47.8
16      3       10       46.6
17      4        0       53.3
18      4        5       54.2
19      4       10       55.3
20      X        0       72.0
21      X        5       57.1
22      X       10       53.4

What shoud I do if I want the table to look like a pivot table with the rows as id and columns as score? Namely,

        0      5     10
101    61.8    70.3  62.2
2      41.0    40.4  44.5
...
Jaap
  • 81,064
  • 34
  • 182
  • 193
Winston
  • 63
  • 6

1 Answers1

0

We can use spread from tidyr. If out is the result obtained from summarize output from ddply

library(tidyr)
spread(out, score, group_mean)

Or acast from reshape2

library(reshape2)
acast(out, id~score, value.var='group_mean')

Or using base R

xtabs(group_mean~id+score, out)
akrun
  • 874,273
  • 37
  • 540
  • 662