R reshape2 'Aggregation function missing: defa

2019-01-24 02:02发布

This question already has an answer here:

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

标签: r reshape2
1条回答
虎瘦雄心在
2楼-- · 2019-01-24 02:40

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

查看更多
登录 后发表回答