【问题标题】:Reshaping data with reshape2 in R在 R 中使用 reshape2 重塑数据
【发布时间】:2015-02-12 16:05:09
【问题描述】:

我一直在试图弄清楚 melt 和 cast 函数如何与 reshape2 包一起使用。但无法得到我正在寻找的结果。

这是数据:

data <- read.table(header=T, text="
  diagnosis  agrp   events  Period
  COPD  1   16  1998-1999
  COPD  2   51  1998-1999
  COPD  3   27  1998-1999
  COPD  4   9   1998-1999
  COPD  1   44  2000-2001
  COPD  2   122 2000-2001
  COPD  3   39  2000-2001
  COPD  4   12  2000-2001")

这就是我想要实现的目标

diagnosis   agrp    1998-1999   2000-2001   etc...
  COPD      1          16        44
  COPD      2          51        12
  COPD      3          27        39
  COPD      4          9         12

我想转置数据,使“期间”成为自己的一列。非常感谢有足够的代码来实现这一点!

更新

这是我的数据的样子:

     data <- read.table(header=T, text="
 diagnosis  agrp    1998-1999   2000-2001
KONTROLL    1     140903      72208
KONTROLL    2     88322       33704
KONTROLL    3     18175       3804
KONTROLL    4     6125        797")

这就是我想要实现的目标:

 diagnosis  agrp    1998-1999   2000-2001   Total
KONTROLL    1     140903       72208        213111
KONTROLL    2     88322        33704        122026
KONTROLL    3     18175        3804       21979
KONTROLL    4      6125         797         6922

【问题讨论】:

  • 也可能看起来像here

标签: r casting reshape2 melt


【解决方案1】:

试试

reshape(data, idvar=c('diagnosis', 'agrp'),
              timevar='Period', direction='wide')
#   diagnosis agrp events.1998-1999 events.2000-2001
#1      COPD    1               16               44
#2      COPD    2               51              122
#3      COPD    3               27               39
#4      COPD    4                9               12

或使用reshape2

library(reshape2)
dcast(data, diagnosis+agrp~Period, value.var='events')
#    diagnosis agrp 1998-1999 2000-2001
#1      COPD    1        16        44
#2      COPD    2        51       122
#3      COPD    3        27        39
#4      COPD    4         9        12

或者

library(tidyr)
spread(data, Period, events)
#   diagnosis agrp 1998-1999 2000-2001
#1      COPD    1        16        44
#2      COPD    2        51       122
#3      COPD    3        27        39
#4      COPD    4         9        12

更新

基于新数据

  transform(data, Total=rowSums(data[,3:4]), check.names=FALSE)
  #  diagnosis agrp 1998-1999 2000-2001  Total
  #1  KONTROLL    1    140903     72208 213111
  #2  KONTROLL    2     88322     33704 122026
  #3  KONTROLL    3     18175      3804  21979
  #4  KONTROLL    4      6125       797   6922

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多