2017-01-30 1 views
0

최근 Stata에서 R로 마이그레이션했습니다. 그룹화 된 또는 그룹화되지 않은 관측에 대해 설명적인 통계를 계산하는 방법을 확신 할 수 없습니다.그룹화 된 또는 그룹화되지 않은 관측에 대한 설명 통계

dput(DF) 
structure(list(Product_Name = c("iPhone", "iPhone", "iPhone", 
"iPhone", "iPhone", "iPhone", "Nexus 6P", "Nexus 6P", "Nexus 6P", 
"Nexus 6P", "Nexus 6P", "Nexus 6P"), Product_Type = c("New", 
"New", "Refurbished", "New", "New", "Refurbished", "Refurbished", 
"Refurbished", "Refurbished", "Refurbished", "Refurbished", "Refurbished" 
), Year = c(2006, 2011, 2009, 2008, 2011, 2009, 2012, 2007, 2013, 
2015, 2009, 2010), Units = c(100, 200, 300, 400, 500, 600, 700, 
200, 120, 125, 345, 340)), .Names = c("Product_Name", "Product_Type", 
"Year", "Units"), row.names = c(NA, 12L), class = "data.frame") 

내 데이터 년 유형에 의해 판매되는 제품이 있습니다

여기 내 데이터입니다. 각 제품은 리퍼 비시 제품 또는 신제품 일 수 있습니다. 또한 2010 년 이전에 판매 된 경우 '시간 1'에 판매 된 것으로 표시하고 그렇지 않은 경우 '시간 2'에 판매 된 것으로 표시합니다.

여기이 내 코드입니다 :

DF[DF$Year<2010,"Time"]<-"1" 
DF[DF$Year>=2010,"Time"]<-"2" 

을 지금, 나는이 기간에 대한 기술 통계를 생성합니다. 우리는 위의 코드를 실행하면

DF %>% 
    group_by(Product_Name, Product_Type,Time) %>% 
    dplyr::summarise(Count = n(), 
        Sum_Units = sum(Units,na.rm=TRUE), 
        Avg_Units = mean(Units,na.rm = TRUE), 
        Max_Units=max(Units,na.rm = TRUE)) 

, 우리는 Product_Name, Product_Type으로 기술 통계를 얻을 것이며, Time는 (즉 기술 통계를 분류). 그러나 이것은 내가 원하는 것이 아닙니다. Product_TypeTime으로 그룹화를 고려하거나 고려하지 않고 설명 통계를 원합니다. 즉, 위의 그룹화 된 정보 중 일부를 유지하면서 제품이 Time 1 또는 Time 2 (즉, 모든 연도) 및 판매 된 제품의 유형에 관계없이 판매되었다고 가정 할 때 설명 통계를 계산할 수 있습니다.

예상 출력 : 출력에서 ​​

dput(DFOut) 
structure(list(Product_Name = c("iPhone", "Nexus 6P"), New_Units_Sum_Time1 = c(500, 
NA), Refurbished_Units_Sum_Time_1 = c(900, 545), Sum_Units_Time1 = c(1400, 
545), Sum_Units_Time2 = c(700, 1285), Sum_Units_Time_1_And_2 = c(2100, 
1830), Avg_Units_Time1 = c(350, 272.5), Avg_Units_Time2 = c(350, 
321.25), Avg_Units_Time_1_And_2 = c(350, 305), Max_Units_Time1 = c(600, 
345), Max_Units_Time2 = c(500, 700), Max_Units_Time_1_And_2 = c(600, 
700)), .Names = c("Product_Name", "New_Units_Sum_Time1", "Refurbished_Units_Sum_Time_1", 
"Sum_Units_Time1", "Sum_Units_Time2", "Sum_Units_Time_1_And_2", 
"Avg_Units_Time1", "Avg_Units_Time2", "Avg_Units_Time_1_And_2", 
"Max_Units_Time1", "Max_Units_Time2", "Max_Units_Time_1_And_2" 
), row.names = 1:2, class = "data.frame") 

, 당신은 내가 몇 가지 기술 통계를 볼 것입니다 :

A) 제품의 종류가 판매 된 기간에 따라 (예를 들어, New_Units_Sum_Time1NewTime1). 출력에서 NewTime1의 조합 만 표시했음을 유의하십시오. RefurbishedTime의 다른 조합에 대한 설명 통계를 작성하는 방법을 알려 주시면 정말 좋을 것입니다. 제품의 형태를 무시하지만 판매 된 제품주기의 두 종류 (예컨대 Sum_Units_Time_1_And_2)를 무시에 기초하여 판매 기간 (예컨대 Sum_Units_Time1Time1)

C)를 무시하는 여부에 기초

b).

평균 및 평균값입니다.

어떻게하면됩니까? 나는 어떤 도움을 주셔서 감사합니다. 나는 이것에 정말로 고심하고있다.


Excel을 사용하여 수동으로 DFOut을 만들었습니다. 비록 내가 그것을 세 번 확인했지만, 몇 가지 수동 오류가있을 수 있습니다 - 나는 질문이있는 경우 그들을 명확히하는 것보다 더 행복 할 것입니다. 시간 내 주셔서 감사합니다.


sessionInfo()

R version 3.3.2 (2016-10-31) 
Platform: x86_64-w64-mingw32/x64 (64-bit) 
Running under: Windows >= 8 x64 (build 9200) 

locale: 
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C       
[5] LC_TIME=English_United States.1252  

attached base packages: 
[1] grDevices datasets stats  graphics grid  tcltk  utils  methods base  

other attached packages: 
[1] tables_0.8    Hmisc_4.0-2    Formula_1.2-1   survival_2.40-1   
[5] ResourceSelection_0.3-0 magrittr_1.5   stringr_1.1.0   bit64_0.9-5    
[9] bit_1.1-12    tufterhandout_1.2.1  knitr_1.15.1   rmarkdown_1.3   
[13] tufte_0.2    corrplot_0.77   purrr_0.2.2    readr_1.0.0    
[17] tibble_1.2    tidyverse_1.1.1   cowplot_0.7.0   plotly_4.5.6   
[21] ggplot2_2.2.1   maps_3.1.1    directlabels_2015.12.16 tidyr_0.6.1    
[25] ggthemes_3.3.0   R2HTML_2.3.2   lubridate_1.6.0   xts_0.9-7    
[29] zoo_1.7-14    lattice_0.20-34   corrgram_1.10   hexbin_1.27.1   
[33] sm_2.2-5.4    compare_0.2-6   installr_0.18.0   psych_1.6.12   
[37] reshape2_1.4.2   readstata13_0.8.5  pastecs_1.3-18   boot_1.3-18    
[41] vcd_1.4-3    car_2.1-4    xlsxjars_0.6.1   rJava_0.9-8    
[45] debug_1.3.1    dplyr_0.5.0    foreign_0.8-67   gmodels_2.16.2   
[49] openxlsx_4.0.0   plyr_1.8.4    

loaded via a namespace (and not attached): 
[1] minqa_1.2.4   colorspace_1.3-2 class_7.3-14  modeltools_0.2-21 mclust_5.2.2  
[6] rprojroot_1.2  htmlTable_1.9  base64enc_0.1-3  MatrixModels_0.4-1 flexmix_2.3-13  
[11] mvtnorm_1.0-5  xml2_1.1.1   codetools_0.2-15 splines_3.3.2  mnormt_1.5-5  
[16] robustbase_0.92-7 jsonlite_1.2  nloptr_1.0.4  pbkrtest_0.4-6  broom_0.4.1   
[21] cluster_2.0.5  kernlab_0.9-25  httr_1.2.1   backports_1.0.5  assertthat_0.1  
[26] Matrix_1.2-7.1  lazyeval_0.2.0  acepack_1.4.1  htmltools_0.3.5  quantreg_5.29  
[31] tools_3.3.2   gtable_0.2.0  Rcpp_0.12.9   trimcluster_0.1-2 gdata_2.17.0  
[36] nlme_3.1-128  iterators_1.0.8  fpc_2.1-10   lmtest_0.9-34  lme4_1.1-12   
[41] rvest_0.3.2   gtools_3.5.0  dendextend_1.4.0 DEoptimR_1.0-8  MASS_7.3-45   
[46] scales_0.4.1  TSP_1.1-4   hms_0.3    parallel_3.3.2  SparseM_1.74  
[51] RColorBrewer_1.1-2 gridExtra_2.2.1  rpart_4.1-10  latticeExtra_0.6-28 stringi_1.1.2  
[56] gclus_1.3.1   mvbutils_2.7.4.1 foreach_1.4.3  checkmate_1.8.2  seriation_1.2-1  
[61] caTools_1.17.1  prabclus_2.2-6  bitops_1.0-6  evaluate_0.10  htmlwidgets_0.8  
[66] R6_2.2.0   gplots_3.0.1  DBI_0.5-1   haven_1.0.0   whisker_0.3-2  
[71] mgcv_1.8-16   nnet_7.3-12   modelr_0.1.0  KernSmooth_2.23-15 viridis_0.3.4  
[76] readxl_0.1.1  data.table_1.10.0 forcats_0.2.0  digest_0.6.12  diptest_0.75-7  
[81] stats4_3.3.2  munsell_0.4.3  registry_0.3  viridisLite_0.1.3 quadprog_1.5-5  
+1

기본적으로 매번 다른 그룹화 변수가 필요합니다 ...? 일련의'group_by %> % ... %> % ungroup() .... %> % ... group_by..'? – Sotos

+0

@Sotos - 항상 도와 주셔서 다시 한 번 감사드립니다. 네, 단 한 가지 명확한 설명은 여러 개의 레이어가 있다는 것입니다 : a) 제품 이름, 시간 및 유형에 따라 그룹화 된 b) 제품 이름, 시간 c)에 따라 그룹화 된 제품 이름에 따라 그룹화 된 a) 설명 통계. 그게 도움이 되니? – watchtower

+1

음, 그렇습니다. 그게 내가 정확히 이해할 수있다. :) – Sotos

답변

2

한 가지 방법이 먼저 그룹화 변수의 가능한 모든 조합 벡터 (ind)를 만드는 것입니다 자동화. 그런 다음 조합을 가져와 Units의 수식으로 변환합니다. 각 수식이 목록 (l1)에 저장되면 해당 목록을 반복하여 집계합니다.

ind <- unlist(sapply(c(2,3), function(i) combn(c('Product_Name', 'Product_Type', 'Time'), 
                  i, paste, collapse = '+'))) 

l1 <- sapply(ind, function(i) as.formula(paste('Units ~ ', i))) 

lapply(l1, function(i) aggregate(i, df, FUN = function(j) c(sum1 = sum(j), 
                  avg = mean(j), 
                  max_units = max(j)))) 

#which gives 

#$`Product_Name+Product_Type` 
# Product_Name Product_Type Units.sum1 Units.avg Units.max_units 
#1  iPhone   New  1200  300    500 
#2  iPhone Refurbished  900  450    600 
#3  Nexus 6P Refurbished  1830  305    700 

#$`Product_Name+Time` 
# Product_Name Time Units.sum1 Units.avg Units.max_units 
#1  iPhone 1 1400.00 350.00   600.00 
#2  Nexus 6P 1  545.00 272.50   345.00 
#3  iPhone 2  700.00 350.00   500.00 
#4  Nexus 6P 2 1285.00 321.25   700.00 

#$`Product_Type+Time` 
# Product_Type Time Units.sum1 Units.avg Units.max_units 
#1   New 1  500.00 250.00   400.00 
#2 Refurbished 1 1445.00 361.25   600.00 
#3   New 2  700.00 350.00   500.00 
#4 Refurbished 2 1285.00 321.25   700.00 

#$`Product_Name+Product_Type+Time` 
# Product_Name Product_Type Time Units.sum1 Units.avg Units.max_units 
#1  iPhone   New 1  500.00 250.00   400.00 
#2  iPhone Refurbished 1  900.00 450.00   600.00 
#3  Nexus 6P Refurbished 1  545.00 272.50   345.00 
#4  iPhone   New 2  700.00 350.00   500.00 
#5  Nexus 6P Refurbished 2 1285.00 321.25   700.00 
+0

Thanks Sotos ... 당신의'df'를'DF1'으로 바꿨고, 다음과 같은 에러가 난다 :'Error in eval (expr, envir, enclos) : object 'Units'not found' . 여기에 추적 표시가 있습니다 :'10.7.stats :: model.frame (수식 = i, data = enf) 9.eval (predvars, data, env) 8.model.frame.default (수식 = i, data = DF1) DF1) 6.eval (expr, envir, enclos) 5.eval (m, parent.frame()) 4.aggregate.formula (i, DF1, FUN = function (j) c (sum1 = sum 1. 집합 (i, DF1, ..2.FUN (X [[i]], ...) 1. lapply (l1, function (i), max_units = max (j)) aggregate (i, DF1, .. – watchtower

+0

hmm ... 잘 모르겠다. 이상하게 여기있다. 완벽하게 작동한다. 최신 버전을 사용하고 있습니까? – Sotos

+0

패키지를 추가했습니다. R을 설치하십시오 – watchtower

관련 문제