R中的reshape2库出现警告信息:缺少聚合函数,将默认使用长度。

20
我曾在 Stack Overflow 上多次看到这个 reshape2,但没有看到适用于我的特定问题的解决方案;
我有一个像这样的数据集;
head(data)
student    test    score
Adam      Exam1     80
Adam      Exam2     90
John      Exam1     70
John      Exam2     60

我正在尝试将它转换为一种宽格式,看起来像这样:

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

使用;

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

但最终数据看起来会像这样:

Student    Exam1     Exam2
Adam        0          0
John        0          1

出现这个错误;

Aggregation function missing: defaulting to length

你有什么想法,为什么它会将所有这些值更改为0或1?


1
你需要提供一个序列列。但是,根据这个例子,它可以通过 dcast(data, student~test, value.var='score') 运行。请提供一个包含重复行的示例。 - akrun
6
这不是一个错误,而是一个警告,提醒你由于没有为 fun.aggregate 提供值(例如 fun.aggregate=mean),它会默认返回长度,也就是该组合类别的行数计数。我在你的示例数据中没有看到 job_type,你希望使用 dcast(data,student ~ test ,value.var='score') 吗? - eipi10
2
嗨,我现在有类似的问题,但我不知道该如何解决。问题是value.var类型错误吗? - Bobesh
2
@Bobesh:虽然时间有点久了,但仍然适用:有时候一个简单的 object <- unique(object) 就可以解决问题,因为问题可能是由于重复行造成的。 - AlexDeLarge
@AlexDeLarge 在这种情况下,“object”是什么? - Vijay Ramesh
@VijayRamesh 在数据框架/数据表、向量和数组上工作。 - AlexDeLarge
1个回答

19

感谢 @akrun 指出。

嗯,你的数据很可能有重复的行,看起来像这样:

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

或者像这样:

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

当您以这种方式转换时:dcast(data, student + class ~ test, value.var='score')


4
仍然出现与上述相同的错误。我按照您的建议操作了。您有什么想法吗? - Vijay Ramesh
2
我尝试了dcast(data, student ~ test, value.var='score'),但它给出了相同的错误和一个0-1矩阵。 - Ami
可能值得检查一下是否存在重复行,可能是由于缺失值导致的。 - M.G.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接