【问题标题】:Unexpected results with cast()cast() 的意外结果
【发布时间】:2011-09-15 14:01:58
【问题描述】:

我正在尝试使用 Reshape 库中的 cast() 投射数据,但我得到了意想不到的结果。我从一个包含大量数据的数据框开始,all_ia[all_ia$Student.ID == 102050,] 返回

66     102050        1      Mar
67     102050        0      Dec
68     102050        1      May
69     102050        0      Feb

其中变量分别是 Student.ID、 Proficiency.Level 和 testmonth。

有一些 Student.ID 是第 5 个月,即 9 月。

当我运行all_ia.cast <- cast(all_ia, Student.ID ~ testmonth, value=c("Proficiency.Level"), fill=c("NA")) 然后运行all_ia.cast[all_ia.cast$Student.ID == 102050,] 时,我得到了意想不到的结果:

1325    102050    1    1    1    1    NA

其中变量分别是 Student.ID、Dec、Feb、Mar、May、Sep。当我运行cast() 时出现警告,上面写着Aggregation requires fun.aggregate: length used as default。

我的问题是,为什么需要 fun.aggregate 以及为什么演员阵容中的 Dec 和 Feb 变量等于 1 而不是 0?

感谢您的帮助!

【问题讨论】:

    标签: r casting reshape


    【解决方案1】:

    这是因为您的转换公式Student.Id ~ tesmonth 不包含您的data.frame 中的所有变量,即不包括Proficiency.Level。

    这意味着,一般来说,强制转换必须执行聚合,聚合公式默认为length。

    您似乎有一个特殊情况,每个学生的月份和熟练程度之间存在一对一的关系。因此,您应该选择一个保留数据的聚合函数,例如采取mean 以下应该工作:

    cast(all_ia, Student.ID ~ testmonth, value=mean("Proficiency.Level"))
    

    您不提供测试数据,因此未进行测试。

    【讨论】:

    • 谢谢!您在上面建议的演员阵容无法逐字逐句,但all_ia.cast <- cast(all_ia, Student.ID ~ testmonth, value=c("Proficiency.Level"),fun.aggregate=mean) 可以。
    • 作为后续问题,为什么在一对一关系的情况下会调用聚合函数?我觉得我过去没有遇到过这种关系的其他数据。
    • 我不确定。 cast 是否有可能猜测,但您有重复的行?
    猜你喜欢
    • 2012-04-02
    • 2019-05-14
    • 2017-07-11
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多