2012-05-24 4 views
1

두 개의 키 열이있는 데이터 프레임이 있으며 세 가지 유형이 있습니다.데이터 프레임의 각 요약 행을 유형 카운트로 확장합니다.

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

이것은 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의 종이있다.

+0

는'reshape'와'reshape2' 패키지의 차이점은 무엇입니까? –

+2

@BlueMagister - reshape2는 프로그래밍에 대해 더 많이 배웠기 때문에 원본 코드를 꽤 많이 재 작성했습니다. 그는 두 번째 반복에서 속도와 일부 기능을 향상 시켰지만 이전 기능과의 호환성을 일부 잃고 싶지 않았습니다. 그는 여기에 대해 더 많은 것을 설명합니다 : http://r.789695.n4.nabble.com/R-pkgs-reshape2-a-reboot-of-the-reshape-package-td2534378.html. 대부분의 경우 reshape2를 사용하는 것이 좋습니다. – Chase

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 기능이 패키지의 표준 세트가 아닌 모양 변경 또는 resshape2 패키지입니다. 참고)

관련 문제