r reshape2 melt返回警告if(drop.margins){:条件有长度> 1,只使用第一个元素

时间:2018-02-20 21:43:40

标签: r reshape reshape2 melt

我有一段代码会返回一条警告消息:

.fillna()

来自Warning in if (drop.margins) { : the condition has length > 1 and only the first element will be used reshape2函数的深层,如错误消息中所示。

我该如何纠正?

代码难以分组,所以我已经包含了数据框的描述。我只是在寻找一个提示。

melt

BTW:S_Flattened是由早期声明中的演员创建​​的:

S_Melted <- melt(S_Flattened, S_Flattened$db_date)

Here's the description of the S_Flattened data frame

1 个答案:

答案 0 :(得分:1)

这里有几个问题:

  1. 您实际上正在使用&#34;重塑&#34;包裹,而不是&#34; reshape2&#34;。
  2. 您正在指定值向量作为&#34; id&#34;变量,因此这个警告。
  3. 请考虑以下事项:

    long <- structure(list(ID = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("A", 
        "B", "C"), class = "factor"), variable = structure(c(1L, 1L, 
        1L, 2L, 2L, 2L), .Label = c("V1", "V2"), class = "factor"), value = 1:6), 
        .Names = c("ID", "variable", "value"), row.names = c(NA, 6L), class = "data.frame")
    

    使用来自&#34的cast重塑&#34;给你一些看起来像data.frame但有一堆其他属性的东西。

    reshape_df <- reshape::cast(long, ID ~ variable)
    str(reshape_df)
    # List of 3
    #  $ ID: Factor w/ 3 levels "A","B","C": 1 2 3
    #  $ V1: int [1:3] 1 2 3
    #  $ V2: int [1:3] 4 5 6
    #  - attr(*, "row.names")= int [1:3] 1 2 3
    #  - attr(*, "idvars")= chr "ID"
    #  - attr(*, "rdimnames")=List of 2
    #   ..$ :'data.frame':  3 obs. of  1 variable:
    #   .. ..$ ID: Factor w/ 3 levels "A","B","C": 1 2 3
    #   ..$ :'data.frame':  2 obs. of  1 variable:
    #   .. ..$ variable: Factor w/ 2 levels "V1","V2": 1 2
    

    这是您的warning

    reshape::melt(reshape_df, reshape_df$ID)
    #      ID value variable
    # V1    A     1       V1
    # V1.1  B     2       V1
    # V1.2  C     3       V1
    # V2    A     4       V2
    # V2.1  B     5       V2
    # V2.2  C     6       V2
    # Warning message:
    # In if (drop.margins) { :
    #   the condition has length > 1 and only the first element will be used
    

    同样的事情,没有warning

    reshape::melt(reshape_df, id = "ID")
    #      ID value variable
    # V1    A     1       V1
    # V1.1  B     2       V1
    # V1.2  C     3       V1
    # V2    A     4       V2
    # V2.1  B     5       V2
    # V2.2  C     6       V2
    

    更好的方法是停止使用&#34;重塑&#34;并开始使用&#34; reshape2&#34;,&#34; data.table&#34; (它提供了比meltdcast更灵活的实现,而不是&#34; reshape2&#34;确实),或者&#34; tidyr&#34;。

    这里使用&#34; reshape2&#34;进行相同的步骤:

    reshape2_df <- reshape2::dcast(long, ID ~ variable)
    

    您返回标准data.frame,没有额外属性。

    str(reshape2_df)
    # 'data.frame': 3 obs. of  3 variables:
    #  $ ID: Factor w/ 3 levels "A","B","C": 1 2 3
    #  $ V1: int  1 2 3
    #  $ V2: int  4 5 6
    

    melt也不是问题 - 只是没有提供矢量,就像你在尝试时那样。

    reshape2::melt(reshape2_df, "ID")
    #   ID variable value
    # 1  A       V1     1
    # 2  B       V1     2
    # 3  C       V1     3
    # 4  A       V2     4
    # 5  B       V2     5
    # 6  C       V2     6