2016-10-18 2 views
1

dcast에서 dplyr를 사용하여 테이블과 같은 피벗을 만들었습니다. 이렇게하는 것이 더 효율적인 방법이 있는지 궁금합니다.Pivot-Like Table in R

library(dplyr) 
library(reshape2) 

state.x77 <- as.data.frame(state.x77) 

state.x77$Population_bucket <- ifelse(state.x77$Population >= 
10000,'Large',ifelse(state.x77$Population >= 1000,'Medium',"Small")) 
state.x77$Income_bucket <- ifelse(state.x77$Income >= 
4700,'High',ifelse(state.x77$Income >= 4100,'Medium',"Low")) 

dcast(state.x77 %>% 
group_by(Income_bucket, Population_bucket) %>% 
summarise(sum(Area)), 
Income_bucket ~ Population_bucket) 
+0

'(Income_bucket , Population_bucket), sum))'네가 행복하지 않은 부분은, dcast? – rawr

+0

더 효율적인 방법이 있는지 확인하십시오. 이 기능을 만들고 싶습니다. 너는 도움이 될 수 있니? – blakeowens15

답변

0

은 여러 가지 방법으로는 R이 같은 테이블을 작성하고 dcast는 잘 하나있다. 코딩 측면에서 ifelse 대신 cut 함수를 사용하여 그룹화 열을 만들고 그룹화를 dplyr 체인 내에서 수행 할 수 있습니다. 또한 dcast 내부에 체인을 포함하는 대신 체인의 끝에 dcast을 호출하는 것이 더 분명 할 수 있습니다. 예를 들어 :

Income_bucket Small Medium Large 
1   Small 9267 740233  NA 
2  Medium 411498 662657 348075 
3   Large 754001 351123 259940 

당신이 출력 테이블을 만들려면

labs = c("Small","Medium","Large") 

state.x77 %>% 
    group_by(Population_bucket = cut(Population, breaks=c(0, 1000, 10000, Inf), 
            labels= labs, right=FALSE), 
      Income_bucket = cut(Income, breaks=c(0, 4100, 4700, Inf), 
           labels=labs, right=FALSE)) %>% 
    summarise(sum(Area)) %>% 
    dcast(Income_bucket ~ Population_bucket) 
는 인간이 읽을 수 있도록, 당신은 또한 천 단위 구분 기호로, 값, 말을 포맷 할 수 있습니다.

summarise(format(sum(Area), big.mark=",")) %>% 

을 그리고 출력은 다음과 같습니다 :이 경우, summarise 라인은 다음과 같이 바꿀 수

(state.x77, tapply (지역, 목록
Income_bucket Small Medium Large 
1   Small 9,267 740,233 <NA> 
2  Medium 411,498 662,657 348,075 
3   Large 754,001 351,123 259,940