【问题标题】:Melt and dcast based on the name of the original data frame column根据原始数据框列的名称进行melt和dcast
【发布时间】:2011-11-09 10:49:27
【问题描述】:

我很难重塑数据框以用于误差线图,将所有列与中心趋势数据结合起来,并分别将所有列与错误数据结合起来。

我从一个数据框开始,其中有一列表示自变量,然后是每个测量参数的两列:一列用于平均值,一列用于误差,因为您通常会使用这种类型的电子表格来格式化数据。初始数据框如下所示:

df<-data.frame(
  indep=1:3, 
  Amean=runif(3), 
  Aerr=rnorm(3), 
  Bmean=runif(3), 
  Berr=rnorm(3)
)

我想使用 melt 和 dcast 将其变成如下所示的形式:

df.cast<-data.frame(
  indep=rep(1:3, 2), 
  series=c(rep("A", 3), 
  rep("B", 3)), 
  means=runif(6), 
  errs=rnorm(6)
)

这样我就可以像这样将它提供给 ggplot:

qplot(data=df.cast, x=indep, y=means, ymin=means-errs, ymax=means+errs, 
      col=series, geom="errorbar")

我一直在尝试融化,然后使用这样的表达式重铸:

df.melt<-melt(df, id.vars="indep")
dcast(df.melt, 
  indep~(variable=="Amean"|variable=="Bmean") + (variable=="Aerr"|variable=="Berr")
)

但是这些返回一个带有有趣的布尔列的数据框。

我可以手动制作两个数据框(一个用于平均值,一个用于错误),分别融化它们,然后重新组合,但肯定有更优雅的方法吗?

【问题讨论】:

    标签: r reshape


    【解决方案1】:

    我会这样做:

    # Melt the data
    
    mdf <- melt(df, id.vars="indep")
    
    # Separate the series from the statistic with regular expressions
    
    mdf$series <- gsub("([A-Z]).*", "\\1", mdf$variable)
    mdf$stat <- gsub("[A-Z](.*)", "\\1", mdf$variable)
    
    # Cast the data (after dropping the original melt variable
    
    cdf <- dcast(mdf[, -2], indep+series ~ stat)
    
    # Plot
    
    qplot(data=cdf, x=indep, y=mean, ymin=mean-err, ymax=mean+err, 
        colour=series, geom="errorbar")
    

    【讨论】:

      【解决方案2】:

      您可以在基础 R 中使用 reshape 来完成它

      df.cast <- reshape(df, varying = 2:5, direction = 'long', timevar = 'series',
        v.names = c('mean', 'err'), times = c('A', 'B'))
      qplot(data = df.cast, x = indep, y = mean, ymin = mean - err, ymax = mean + err, 
        colour = series, geom = "errorbar")
      

      【讨论】:

      • +1 用于 reshape() 示例。除非您确实需要使用名称“时间”而不是“系列”才能使其正常工作
      • 这是默认值,reshape 使用。可以通过在调用中设置timevar = series 来更改它。我已经编辑了我的解决方案以反映这一点。
      • 这也很有帮助。 reshape 的帮助页面确实需要重写。我花了 4 年,没有 9 年的时间来学习有效地使用它。
      • 我正在整理一组简短的 2-3 张幻灯片,这应该可以让使用reshape 变得超级容易(希望如此)
      猜你喜欢
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2021-12-16
      • 1970-01-01
      • 2021-03-29
      • 2013-02-16
      相关资源
      最近更新 更多