1

次のようなデータ フレームがあります。2 つのキー列と、3 つの異なる種類のデータの数があります。

  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

これを無痛にする機能はありますか?

4

2 に答える 2

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
...

統計ソフトウェアのジャーナルに、始めるのに最適な論文があります。

于 2012-05-24T19:01:52.137 に答える
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 パッケージには含まれていないことに注意してください。)

于 2012-05-24T19:02:03.007 に答える