【问题标题】:Usage of the casting in reshape2 for partial pivoting使用 reshape2 中的铸件进行部分枢转
【发布时间】:2017-04-15 01:44:50
【问题描述】:

我不确定这是否符合旋转的条件,这就是为什么我想我会问小组的原因。我不确定如何从下面的输入到输出数据帧。我用逗号分隔它们,因为我找不到创建表的方法。

输入:

标题:key1、key2、key3、类型、值

值:

    a1, b1, c1, fruit,     1
    a1, b1, c1, vegetable, 3
    a2, b2, c2, fruit,     7
    a2, b2, c2, vegetable, 11
    a2, b2, c2, nut,       13

输出:

标题:key1、key2、key3、水果、蔬菜、坚果

价值观:

    a1, b1, c1, 1,  3, 
    a2, b2, c2, 7, 11, 13

也就是说,我希望认识到“类型”列有不同的选择(水果、蔬菜、坚果),并为每个选项创建一个列并将值放入其中。由于没有 a1、b1、c1 的 nut 值,我将其留空。

它真的还在旋转还是有其他方法可以做到这一点?非常感谢!

【问题讨论】:

    标签: r dplyr tidyr reshape2


    【解决方案1】:

    意识到这比当时看起来要容易。 dcast(myDataFrame, key1 + key2 + key3 ~ type, value.var = "value") 做到了。

    【讨论】:

      【解决方案2】:

      tidyr:spread(type, value)

      将快速轻松地将您的帧从长格式转换为宽格式。

      [使用您的“农场”数据框dput()-ed。]

      > dput(farmstand)
      structure(list(key1 = c("a1", "a1", "a2", "a2", "a2"), key2 = c("b1", 
      "b1", "b2", "b2", "b2"), key3 = c("c1", "c1", "c2", "c2", "c2"
      ), type = c("fruit", "vegetable", "fruit", "vegetable", "nut"
      ), value = c(1, 3, 7, 11, 13)), .Names = c("key1", "key2", "key3", 
      "type", "value"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
      -5L))
      
      > farmstand %>% spread(type, value)
      # A tibble: 2 × 6
         key1  key2  key3 fruit   nut vegetable
      * <chr> <chr> <chr> <dbl> <dbl>     <dbl>
      1    a1    b1    c1     1    NA         3
      2    a2    b2    c2     7    13        11
      

      请在此处查看更多酷炫、快速和简单的数据整理技巧:data-wrangling-cheatsheet

      【讨论】:

        猜你喜欢
        • 2014-02-25
        • 1970-01-01
        • 2013-10-15
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多