繁体   English   中英

r reshape2 融化在 if (drop.margins) { 中返回警告:条件长度 > 1 并且仅使用第一个元素

[英]r reshape2 melt returns Warning in if (drop.margins) { : the condition has length > 1 and only the first element will be used

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

Warning in if (drop.margins) { :
  the condition has length > 1 and only the first element will be used

reshape2 melt函数的深处,如错误消息所示。

我该如何纠正?

代码很难进行子集化,所以我已经包含了数据框的描述。 我只是在寻找提示。

S_Melted <- melt(S_Flattened, S_Flattened$db_date)

顺便说一句: S_Flattened 是由早期语句中的强制转换创建的:

S_Flattened = cast(S, db_date ~ MetricType, value="AvgValue")

这里是 S_Flattened 数据框的描述

这里有几个问题:

  1. 您实际上使用的是“reshape”包,而不是“reshape2”。
  2. 您将值向量指定为“id”变量,因此出现此警告。

考虑以下:

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

使用“reshape”中的cast会给你一些看起来像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

更好的方法是停止使用“reshape”并开始使用“reshape2”、“data.table”(它提供比“reshape2”更灵活的meltdcast实现)或“tidyr”。

这是与“reshape2”相同的一组步骤:

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 ing 也不是问题——只是不要像你在尝试中那样为它提供向量。

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  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM