【问题标题】:Why is it returning a warning when reshaping in R?为什么在 R 中重塑时会返回警告?
【发布时间】:2023-03-05 00:32:02
【问题描述】:

这是我需要宽格式的表格:

V1      V2        V3        V4
1       A0      numeric   string
1       A1         .         .
1       A2         .         .
1       A3         .         .
1       A4         .         .
1       A5         .         .
1       A6         .         .
1       A7         .         .
2       A0         .         .
2       A1         .         .
...     ...        .         .

我一直在尝试这样的事情:

reshape(variable.name, timevar = "V2", idvar = "V1", direction = "wide")

这导致了以下结果,这似乎是我想要的:

V1   V3.A0     V4.A0    V3.A1     ...
1    Numeric   String   Numeric   ...
2    ...       ...      ...       ...

但我收到一条警告消息:

Warning message:
In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
multiple rows match for V2 = blah: first taken

为什么会出现此警告,我该如何规避它?我不想忽略它,因为我必须对几个数据文件做同样的事情。谢谢!非常感谢您的帮助。

【问题讨论】:

  • 假设您的完整数据集位于数据框df 中,列V1... V4。输入anyDuplicated(df[,c("V1","V2")])。如果结果 > 0,则说明某处存在重复,这将导致 @hd1 解释的错误。
  • @jlhoward 谢谢!肯定 >0,但我现在该怎么办?
  • @user,要这样重塑,每个 V1、V2 组合最多需要 1 个条目。所以问题变成了你想对这些多个条目做什么。

标签: r reshape


【解决方案1】:

正如一些人所指出的,您需要决定要如何处理额外的价值。 dcast 允许你指定一个聚合函数,并且本质上与 reshape 相同,方向很宽,但能够指定当你有多个值时要做什么。这是一个示例,基本上每个组合都有重复,我们将每个组合的完整向量显示为一个已解析的字符串(例如 1:2 显示为 c(1, 2))。

library(reshape2)

# Make up data

df <- data.frame(
  V1=rep(1:3, 14), 
  V2=rep(paste0("A", 0:6), 6), 
  V3=sample(1:100, 42), 
  V4=paste0(sample(letters, 42, replace=TRUE), sample(letters, 42, replace=TRUE))  
)    
# Need to melt V3 and V4 together first because
# dcast does not allow multiple value variables,
# unfortunately, this allso coerces V1 to character

df.melt <- melt(df, id.vars=c("V1", "V2")) 

# Function to handle multiple items for one V1 - V2
# pair.  In this case we just deparse the vectors,
# but if you wanted, you could convert the numerics
# back to integers, or do whatever you want (e.g.
# paste if character, median if numeric).

my_func <- function(x) {
  paste0(deparse(x), collapse="")
}
# Now convert to wide format with dcast    

dcast(
  df.melt, 
  V1 ~ V2 + variable,
  value.var="value",
  fun.aggregate=my_func
)

这会导致以下结果:

  V1         A0_V3         A0_V4          A1_V3         A1_V4
1  1 c("86", "93") c("yf", "pr")   c("5", "76") c("py", "aj")
2  2 c("53", "71") c("as", "mi")  c("42", "12") c("ho", "la")
3  3 c("69", "16") c("lm", "un") c("66", "100") c("xk", "px")
          A2_V3         A2_V4         A3_V3         A3_V4         A4_V3
1 c("43", "67") c("xh", "bk") c("79", "94") c("ix", "cx") c("51", "50")
2 c("14", "68") c("nq", "sr") c("25", "19") c("dw", "ay") c("28", "35")
3 c("21", "24") c("wu", "il") c("39", "88") c("vz", "yw") c("74", "65")
          A4_V4         A5_V3         A5_V4         A6_V3         A6_V4
1 c("hv", "uw") c("85", "34") c("cn", "ql") c("73", "87") c("px", "vy")
2 c("qb", "dc")  c("2", "72") c("ci", "du") c("81", "49") c("sd", "rx")
3 c("jk", "fv")  c("6", "90") c("sr", "yr") c("62", "97") c("rg", "dv")    

完美的解决方案是reshape 和dcast 的组合。不幸的是dcast(AFAIK)不允许多个 Z 列,而reshape 允许(因此需要melt 步骤和对字符的强制),而reshape 不允许聚合函数(AFAIK)。

您可以通过运行dcast 两次,一次使用V3,一次使用V4 来解决此问题,然后合并结果,或者在聚合函数中添加更多智能。

【讨论】:

    【解决方案2】:

    如上所述,如果idvar 和timevar(在您的示例中为V1 和V2)的组合不是唯一的,reshape(...) 将生成警告。保证唯一性的一种方法是聚合这两个变量。这也明确了@Arun 的优点,即如果有重复项,您必须决定该怎么做。以下是几个选项。

    set.seed(1)
    # sample dataframe in same format as OP
    type <- c("numeric","string")
    df <- data.frame(V1=rep(1:10,each=8),V2=paste0("A",0:7),
                     V3=type[sample(1:2,80, replace=T)], 
                     V4=type[sample(1:2,80, replace=T)])
    dupes <- df[sample(1:80,10),]   # some random duplicates
    dupes[,3:4] <- type
    df <- rbind(df,dupes)           # append to original df
    
    df.wide <- reshape(df, timevar = "V2", idvar = "V1", direction = "wide")
    # many warnings...
    
    func   <- function(x) head(x,1)   # if duplicate, use first value
    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), func)
    
    func   <- function(x) tail(x,1)   # if duplicate, use last value
    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), func)
    
    # if replicated, indicate number of replications
    func   <- function(x) {ifelse(length(x)==1,as.character(x), length(x))}
    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), func)
    
    # if duplicated, flag as such
    func   <- function(x) {ifelse(length(x)==1,as.character(x),"duplicated")} 
    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), func)
    
    # if duplicates with different V3 or V4, indicate with "both"
    func   <- function(x) {ifelse(length(unique(x))==1,as.character(x),"both")} 
    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), func)
    
    df.wide <- reshape(df.new, timevar = "V2", idvar = "V1", direction = "wide")
    # no warnings - reshape succeeded.
    

    这里有几个细微差别需要解释。注意函数中as.character(x) 的使用。这是因为 R 将 df$V3 和 df$V4 视为因素。使用x 将返回因子水平(1 或2,因为这些因子只有2 个水平)。使用as.character(...) 会强制 R 返回因子标签(“字符串”或“数字”)。

    最后,请注意,您可以将函数定义直接放在对aggregate(...) 的调用中,如:

    df.new <- aggregate(df[c("V3","V4")], by=list(V1=df$V1,V2=df$V2), 
                        function(x) {ifelse(length(x)==1,as.character(x),"both")})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2019-02-21
      • 2021-09-05
      • 2014-07-14
      相关资源
      最近更新 更多