Emery
Emery

Reputation: 31

How can I count the number of instances within one column of a dataframe based on the condition of a pattern within another column?

      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

Assuming this is my dataset, I want to create a new dataframe, that has a unique row for every Year-month combination, a column that counts every residential instance for that date, and a third column with a count for every Commerical count. For instance in this dataset I would have

    Issued Date   commercial  Residential 
    1981-05        2             2  

I have been messing around with tapply, count_(), and other functions with no real good idea.

Upvotes: 0

Views: 41

Answers (1)

www
www

Reputation: 39184

We can use the dplyr and tidyr.

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)

Upvotes: 2

Related Questions