将数据框的每个摘要行展开为类型计数

时间:2012-05-24 18:47:42

标签: r dataframe

我有一个看起来像这样的数据框,有两个关键列,然后有三种不同类型的数据。

  Year Month Urban Suburban Rural
1    1     1    11       12    13
2    1     2    21       22    23

我想扩展每一行,以便将类型列为因子,然后列出该类型中的数字,如下所示:

  Year Month     Type Number
1    1     1    Urban     11
2    1     1 Suburban     12
3    1     1    Rural     13
4    1     2    Urban     21
5    1     2 Suburban     22
6    1     2    Rural     23

是否有一种能够轻松实现这一功能的功能?

2 个答案:

答案 0 :(得分:2)

这正是reshapereshape2包的目的:

require(reshape2)
x <- read.table(text = "Year Month Urban Suburban Rural
1    1     1    11       12    13
2    1     2    21       22    23")

#Specify the variables that are your ID variables. The others will form your "long" data
x.m <- melt(x, id.vars = c("Year", "Month"))
#-----  
Year Month variable value
1    1     1    Urban    11
2    1     2    Urban    21
3    1     1 Suburban    12
...

journal of statistical software中有一篇论文是开始的好地方。

答案 1 :(得分:2)

dat <- read.table(text=" Year Month Urban Suburban Rural
 1    1     1    11       12    13
 2    1     2    21       22    23
 ", header=TRUE)

reshape(dat, direction="long", idvar=1:2, varying=names(dat)[3:5], times=names(dat)[3:5], v.names="Number", timevar="Type")
             Year Month     Type Number
1.1.Urban       1     1    Urban     11
1.2.Urban       1     2    Urban     21
1.1.Suburban    1     1 Suburban     12
1.2.Suburban    1     2 Suburban     22
1.1.Rural       1     1    Rural     13
1.2.Rural       1     2    Rural     23

(请注意,reshape函数位于标准软件包集合中,而不在reshape或resshape2软件包中。)