R reshape2 'Aggregation function missing: defaulting to length'

chattrat423 picture chattrat423 · May 26, 2015 · Viewed 41.4k times · Source

I have seen this reshape2 several times on SO but haven't seen a solution to my particular problem;

I have a dataset like this;

head(data)
student    test    score
Adam      Exam1     80
Adam      Exam2     90
John      Exam1     70
John      Exam2     60

I am trying to cast this to a wide format that looks like this;

Student    Exam1    Exam2 ........ ExamX
Adam         80       90
John         70       60

using;

dcast(data,student~test,value.var='score')

but the data ends up looking like something like this;

Student    Exam1     Exam2
Adam        0          0
John        0          1

with this error;

Aggregation function missing: defaulting to length

Any ideas why it is changing all of these values to a (0 or 1)?

Answer

JelenaČuklina picture JelenaČuklina · Jan 19, 2016

Thanks to @akrun who pointed it out.

Well, there's a high chance that your data has duplicate row that look either like this:

student    test    score
Adam      Exam1     80
Adam      Exam1     85
Adam      Exam2     90
John      Exam1     70
John      Exam2     60

Or like this:

student   class     test    score
Adam      Biology   Exam1     80
Adam      Theology  Exam1     85
Adam      Theology  Exam2     90
John      Biology   Exam1     70
John      Theology  Exam2     60

When you cast it like this: dcast(data, student + class ~ test, value.var='score')