2017-09-16 109 views
0
 IssuedDate PermitClassMapped 
    1 1981-12  Commercial 
    2 2012-12  Residential 
    3 1981-05  Residential 
    4 1981-05  Residential 
    5 1981-05  Commercial 
    6 1981-05  Commercial 

假設這是我的數據集,我想要創建一個新的數據框,該數據框對於每個年份組合都有一個唯一的行,對該日期的每個住宅實例進行計數的列,以及對每一個Commerical計數。例如,在此數據集我會如何基於另一列中的模式條件來計算數據幀的一列內的實例數?

Issued Date commercial Residential 
    1981-05  2    2 

我一直tapply瞎搞,count_()等功能,沒有真正的好主意。

回答

2

我們可以使用dplyrtidyr

library(dplyr) 
library(tidyr) 

dt2 <- dt %>% 
    count(IssuedDate, PermitClassMapped) %>% 
    spread(PermitClassMapped, n, fill = 0) 

dt2 
# A tibble: 3 x 3 
    IssuedDate Commercial Residential 
*  <chr>  <dbl>  <dbl> 
1 1981-05   2   2 
2 1981-12   1   0 
3 2012-12   0   1 

DATA

dt <- read.table(text = "IssuedDate PermitClassMapped 
    1 1981-12  Commercial 
    2 2012-12  Residential 
    3 1981-05  Residential 
    4 1981-05  Residential 
    5 1981-05  Commercial 
    6 1981-05  Commercial", 
       header = TRUE, stringsAsFactors = FALSE) 
+0

這完美的作品,謝謝! – Emery

+0

我很樂意提供幫助。如果這是您正在尋找的解決方案,請接受此答案。 – www

相關問題