0

I have list of people grouped by their counties and by villages. I would like to count the number of villages in the respective counties. I am able to count the number of people in each county.

library(dplyr)

set.seed(123)

df <- data.frame(
  person = 1:100,
  county = round(runif(100, 1, 5)),
  village = round(runif(100, 1, 10))
)

# Number of people per county
df %>% count(county )

Moses
  • 1,391
  • 10
  • 25

2 Answers2

0

Would that work for you Moses

df %>% group_by(county) %>% 
  count(village,county)
LDT
  • 2,856
  • 2
  • 15
  • 32
  • A I see you want to count how many people there are in each village based on the county? – LDT Oct 19 '21 at 09:29
0

library(dplyr)

df %>% 
  group_by(county) %>% 
  add_count(village)

output:

   person county village     n
    <int>  <dbl>   <dbl> <int>
 1      1      2       6     4
 2      2      4       4     8
 3      3      3       5     5
 4      4      5      10     1
 5      5      5       5     3
 6      6      1       9     2
 7      7      3       9     1
 8      8      5       6     2
 9      9      3       5     5
10     10      3       2     6
# ... with 90 more rows
TarJae
  • 72,363
  • 6
  • 19
  • 66